Start learning with our library of video tutorials taught by experts. Get started

Android SDK: Local Data Storage

Retrieving and displaying data


From:

Android SDK: Local Data Storage

with David Gassner

Video: Retrieving and displaying data

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.
Expand all | Collapse all
  1. 6m 34s
    1. Welcome
      50s
    2. What you should know before starting this course
      2m 11s
    3. Using the exercise files
      3m 33s
  2. 21m 6s
    1. Exploring local data storage options
      5m 58s
    2. Configuring Eclipse and the Android Developer Tools
      5m 29s
    3. Creating an Android virtual device
      3m 23s
    4. Creating a new Android project
      6m 16s
  3. 31m 30s
    1. Using preferences in Android apps
      5m 28s
    2. Defining preferences with Java
      9m 31s
    3. Defining shared preferences with an activity
      10m 50s
    4. Listening for changes to shared preferences
      5m 41s
  4. 51m 13s
    1. Creating and reading files in internal storage
      10m 18s
    2. Creating and reading JSON data files
      9m 48s
    3. Working with files in external storage
      11m 22s
    4. Parsing a read-only XML file with XmlPullParser
      11m 46s
    5. Parsing a read-only XML file with JDOM
      7m 59s
  5. 1h 8m
    1. Creating a new SQLite database
      2m 52s
    2. Defining a database with SQLiteOpenHelper
      12m 12s
    3. Managing the database with a DataSource class
      9m 38s
    4. Inserting data into a database table
      10m 29s
    5. Retrieving and displaying data
      11m 44s
    6. Importing data from XML to SQLite
      5m 15s
    7. Filtering and sorting data
      9m 27s
    8. Accessing a database from the command line
      6m 46s
  6. 42m 0s
    1. Improving the data display
      9m 29s
    2. Passing user-selected data to a detail activity
      11m 36s
    3. Working with multiple database tables
      10m 28s
    4. Deleting data from database tables
      10m 27s
  7. 49s
    1. Where to go from here
      49s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Android SDK: Local Data Storage
3h 41m Intermediate Jan 25, 2013

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.

Topics include:
  • Exploring local data storage options
  • Creating an Android virtual device
  • Starting a new project
  • Defining preferences with Java and activities
  • Creating and reading JSON and XML data files
  • Creating a new SQLite database
  • Inserting and retrieving data in the database
Subjects:
Developer Mobile Apps Programming Languages
Software:
Android Java
Author:
David Gassner

Retrieving and displaying data

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.

Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Android SDK: Local Data Storage.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

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.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked