Viewers: in countries Watching now:
Take your Android programming skills to the next level with the Android built-in framework that enables local data management in text files and SQLite-based relational databases. This course shows you how to create datacentric apps for Android devices, using SQLite, Java, and the built-in android.database packages. Author David Gassner describes how to define shared preferences, work with JSON and XML files in internal and external data stores, and create new local SQLite databases.
Once you've inserted data into a database table, the next natural thing you'd like to do is retrieve and display it. I'm working in a new version of the project called RetrieveData. In this project's datasource class, I already have the code to add new rows. It's called the Create Method. And now I'll add code to retrieve all rows and all columns of the same database table. I'll start at the top of the class. I'll define a constant which will be an array of strings. The array will contain one string for each column in the database table.
I'll create it here as a private static final field, I'll data type it as String with opening close bracket, which means it's an array, and I'll name it allColumns. I'll set it using a pair of braces, and then within the braces I'll define a commented limited list of all of my column names. The column name constants are in my OpenHelper class. So I'll start off with ToursDBOpenHelper, and then I'll start with the primary key column, COLUMN_ID, and I'll add a comma.
Now I'll duplicate that line of code four times, and then I'll go back and change the column names. I'll include the title and the description and the price and the image. I don't need the last comma, and I'll close up this code and add the semicolon at the end, and now I have an array of strings that I can use that identifies all of the columns of my database table. Next, I'll create a new method in my data source class that I'll name findAll.
It will retrieve all columns, all rows and return them as a list of tour objects. I'll scroll down to the bottom of the class and I'll add this new code after the create method. As with all these methods, it will be public so that it can be called from anywhere in the application. It will return a list of tours. I'll type in the name of the list class then I'll press Ctrl+Space and choose the class to add the import, and I'll set the data type of its members to Tour.
That's my custom class. The name of the method will be findAll, and it won't receive any arguments. The first two steps in the findAll method are to define the list object and then to query the database. I'll create a list of tour objects, which I'll name Tours, and I'll instantiate it with the ArrayList Constructor Method. Next, I'll query the database. You can query the database either using the ExecuteSQL method for a raw query, or for a simpler approach, to query a single table into database, you can use a method called Query.
If you need to do something more complex, such as joining tables together, you might need to use another method called raw query. I'm going to be querying just the single table, the tours table, so I'll use the query method. The query method returns an instance of class called Cursor. If you're familiar with JDBC programming in Java, the Cursor class is similar to the ResultSet class. It's a reference to the data that's returned from the query. I'll start by typing the name of the class, and then I'll import it from the android.database package.
And I'll name the object Cursor and I'll assign it by calling the Database Query method. I'll type in database and press period, and that opens a list of all the methods of the database object. Notice that there are a few different signatures for the query method. I'll use the second one that starts with the name of the table. For the table name, I'll use a constant of my OpenHelper, ToursDBOpenHelper.TABLE_TOURS.
Then for the columns, I'll pass in my array of strings that I just finished defining named allColumns. All of the rest of these arguments can be set to null. If you like, you can add filters in a couple of different ways, and you can group by and order by. But I'm just going to accept the default order. So I'll type in null for each of these values, and I'll do a little bit of code wrapping to make it a little bit easier to read. Once you've executed the query, you can immediately find out how many rows were returned by using a method of the Cursor object called GetCount.
I'll do some LOGCAT output. I'll use the log class and its I method, I'll pass in my LOGTAG constant and then a message starting with the string Returned and concatenate cursor.getCount, and I'll finish the message with a string of rows. Now remember, this method needs to return a list of tour objects. So I need to loop through the cursor and deal with one row at a time.
Again, if you're familiar with JDBC, you might remember that in a ResultSet, the cursor starts before the first row, and the same thing is true of the SQLite cursor object in Android. So first, I'm going to add some conditional code. I'll use an if statement. And I'll check the count and make sure that it's greater than zero, using the expression if cursor.getCount is greater than zero. Then if this condition is true, I'll loop through the rows.
I'll use a while loop here. I'll type while and press Ctrl+Space, and I'll loop with a condition. The condition will be a call to the method move to next. This is similar to the JDBC ResultSet Next method. I'll type in Cursor., and I see a listing of available methods. There's an isAfterLast and then isBeforeFirst and an isFirst and an isLast, and so on, and I'll choose moveToNext. It returns a boolean value, and if it successfully moves to a new row, it will return true, and if it's already finish with a loop, it will return false.
So then if I successfully move to a new row, I'll create a new instance of the Tour class, which I'll name Tour. Then I'll grab the values from the cursor one at a time using methods of the cursor object that are unique to each data type. So for example, I'll start with tour.setId, and I'll pass in the following code, cursor.getLong. Remember, in a previous exercise, I set the data type of my ID property of the tour object as along, and so I'll call the getLong method now to set the data type correctly.
For the column index that's being requested, you should always call a method called getcolumnIndex and pass in the name of the column. The code looks like this, cursor.getColumnIndex and then pass in the column name, which in this case will be ToursDBOpenHelper.COLUMN_ID. And so that's all the code you need to retrieve a single value of the correct data type and then pass it into a model object. I'll duplicate this code once, and then for the new version, I'll call this setTitle method of the tour object.
When I retrieve the data, instead of setting the data type as Long, I'll set it as a String. And then at the end of the call, I'll change the name of the column that I'm retrieving from COLUMN_ID to COLUMN_TITLE. I'll duplicate that line of code twice, and I'll retrieve both the description and the image. For the description, I'll call the tour object setDescription method. I'm already using a string so I don't need to change the data type, but I do need to change the name of the column to COLUMN_DESC.
Then I'll do the same thing for the image. I'll change setTitle to setImage and I'll change the name from title to image. And finally, I need to deal with the price. I'll go back to the code that's calling setId, I'll duplicate it, I'll move it down a few lines, and I'll change the name of the setMethod to setPrice. I'll change the data type from getLong to getDouble and I'll change the name of the database column to COLUMN_PRICE.
So that's all the code I need to loop through the cursor, retrieve one row at a time, and then add the rows data to the Tour object. At the end of all this code, I'll take that Tour object and add it to my list of tours using tours.add, and I'll add the tour object. Finally, at the end of the loop, I'll return the list object. I'll place the cursor after the entire conditional clause and add return tours.
I see an error indicator showing me that I've missed a semicolon, so I'll add it there, and all the errors are cleared, and it looks like it's good to go. I'll save these changes, and now I'll go back to my main activity. In my MainActivity, I'm currently getting the data from an XML file. Using the XML PullParser to parse the XML file and getting back a list of tours. I'm going to comment that out, and instead, I'm going to get the list of tours from my database.
I move the cursor down here to after the call to open the data source. I'll declare my list of tours, once again calling it tours, and this time I'll call it datasource.findAll. If this is the first time I've run the application, there might not be any data in it. So I'll add a conditional clause, and I'll check the size of the tours object. If tours.size has a value of zero, then I'll take this createData method and I'll move it into the conditional block, and then I'll make a copy of this code and I'll re-execute it.
The second time I call it, I don't need to re-declare the list, it's already declared. So now the entire logic is I'll retrieve all the data. If there isn't any data there, I'll create the data and then I'll retrieve it again. And from that point forward, everything should work exactly the way you want. I already have the code to create an array adaptor and then to pass in the list of tours and display it on the screen. So let's see how we did. I'll run the application in the emulator.
If this is the first time the application has run, it will create the data, and if it's not the first time, it will just read the existing data, and there is the result. The three tours that I created displayed on the screen instead of the data that was retrieved from the XML file. So that's the code you need to retrieve data for display in your application. Again, you put all the code into your data source class, wrap it up in public methods, and then you'll be able to retrieve the data from anywhere in the application.
There are currently no FAQs about Android SDK: Local Data Storage.
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.