New Feature: Playlist Center! Pick a topic and let our playlists guide the way—like a learning mixtape.

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

Android SDK: Local Data Storage
Illustration by Don Barnett

Creating and reading JSON data files


From:

Android SDK: Local Data Storage

with David Gassner

Video: Creating and reading JSON data files

JSON, or JavaScript Object Notation, is a concise structured data format. It's used in Android to move data around the web from server to device, but can also be used to save structured data locally to persistent storage. I'll show you how to use JSON in the Android SDK in this project: JSONDataFiles. The user interface for this version of the project has a very minimal set of controls: two buttons for creating and reading a file and one TextView object to display text.
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

Creating and reading JSON data files

JSON, or JavaScript Object Notation, is a concise structured data format. It's used in Android to move data around the web from server to device, but can also be used to save structured data locally to persistent storage. I'll show you how to use JSON in the Android SDK in this project: JSONDataFiles. The user interface for this version of the project has a very minimal set of controls: two buttons for creating and reading a file and one TextView object to display text.

I'll go to my MainActivity class and scroll down toward the bottom of the code and find the method createFile. In this version of my createFile method I already have code to create a file in internal storage--that is, a file that's local to the current application. But I'll add code here to create a JSON data packet. I'll place the cursor above any of the other code in the method, and I'll start by creating an instance of the class JSONArray. It's spelled J-S-O-N, in all uppercase, and then Array.

And I'll name the object dat'. A JSONArray is a resizable array. You can add as many objects as you want to it and then it will automatically serialize the data into a JSON notation string. I will instantiate the object with the class's constructor method, using new JSONArray. Next, I'll declare an instance of a class called JSONObject, and I'll name that tour. I'm not instantiating it quite yet. I'm just going to start with declaring it.

A JSONObject is a dynamic object that implements the Java Map Interface. You can add values to the JSONObject as key-value pairs. The keys are always strings, but then the values can be anything you want. I'll create a single tour instance. I will instantiate the object using tour = new JSONObject. Then I'll add a couple of properties. I'll name my two properties tour and price.

The tour will be a string--that will be the name of the tour--and the price will be a numeric value. Because I'll be working in JavaScript style, the data types will be dynamically inferred from my syntax. First, I'll create the tour name. I'll call tour.put, and I'll pass in a string of tour and a value of Salton Sea. Because the string Salton Sea is surrounded in quotes, its data type will be a string. Notice that I'm getting a warning icon.

This is telling me I need to add a throws declaration. Whenever you start creating JSON objects or JSON arrays, you might throw an exception called JSONException. I'll add that to the throws clause by clicking on the icon and doing a quick fix. That adds JSONException to the list of exceptions that might be thrown from this method. I'll come back to my call to the put method and I'll duplicate that. Then I'll change the key for the second value from tour to price.

I'll change the value from a string to a number. This is a pure numeric literal, and it will be translated as a numeric data type by the JavaScript notation code. This will be a simple version of an object, and now I'm ready to add it to the array. So, I'll call data.put and I'll pass in the tour object. So, that's all you need to do to create an object and add it to the array. I'll duplicate those lines of code a couple of times. And for the second and third versions, I'll change the tour and price.

For the second tour, the tour property will be Death Valley and the price will be 600. And for the third one, the tour name will be San Francisco and the price will be 1200. Notice that I'm not including a comma here. This is a pure numeric literal. And because we're working in Java 6 compatibility, you can't add an underscore as you might in Java 7. That won't be recognized correctly. Just leave it as is, without the underscore or any other notation, and it will be correctly data typed as a number.

So now my JSONArray is ready to use. And I'll come down here where I'm setting a string variable called text, and I'll get its value by calling the data object's toString method. And that serializes the value to a string, and the string can then be saved to disk. I'm going to change the name of my file. And instead of myfile.txt, I'll name this file tours. I won't use any file extension. Finally, instead of just telling the user that the file was written to disk, I'll actually display the content that was created.

After File written to disk, I'll add a line feed with a \n, and then I'll append to that data.toString. Again, I'm serializing a JSON string. I'll save my changes and run the application in the emulator. When the application opens, I'll click Create file, and I see the message that the file was written to disk, and I see the JSON notation. The square brackets wrapping the entire string mean that it's an array, and each JSONObject is notated with curly braces.

The string values have quotes and the numerics don't. It's pretty easy to read, and it's been written to disk and is ready to use. I'll add code to retrieve and read the file from disk. I'll go back to Eclipse and I'll move down to the method readFile. First, I'll change the name of the file that I'm reading. Once again, instead of myfile.txt, I'll use tours. Then I'll move the cursor down to after the content has been read. I'm going to move a couple of lines of code around.

Before I start processing the JSON content, I want to make sure that I've closed my strings, so I'll move the calls to the close methods up a bit and then I'll place the cursor after the close methods and before the call to displayText. In order to deserialize from a string to a JSON array, declare the JSONArray object, and once again, I'll call it data, and I'll once again use the JSONArray constructor method, but this time I'll pass in the string that contains the JSON-notated content.

I'll pass in b, the StringBuffer, .toString. And now, I've deserialized the content and I'm ready to deal with it as a Java object. Just as I did with the createFile method, I'll do a quick fix and add JSONException to my throws clause. I'll move down to after I've deserialized the data. I'll loop through the array. I'll use a for loop, iterating over an array. My temporary variable will be i, and I'll change the array that I'm reading to data.

Within the for loop, I'll create a string, and I'll name it tour, and I'll call the JSONArray class's getJSONObject method. And I'll pass in the current index that I'm looping on. So now I'm returning a JSONObject, and I want to retrieve just the string value representing the tour name. So, from the JSONObject, I'll call the getString method. Notice that there are methods for getString, getBoolean, double, int, and long. These are the data types that are supported by JSON notation.

I'll call getString, and I'll pass in the key tour. Remember, that's the key that I used when I created the JSON notation. I still have one error in the for loop, and that's because the code template I used when I created my for loop treated length as a property of the data object. But in the JSONArray, it's a method. So, I'll move my cursor after the length property and press Ctrl+Space, and that correctly fills in the method call. So now, I'm retrieving a string for each tour in the array.

I'd like to concatenate them all together into a single string. I'll place the cursor above the for loop, and I'll create a new StringBuffer object, which I'll call toursBuffer, and I'll instantiate it with the constructor method. Then I'll move the cursor back to within the for loop, and I'll take that tour string and I'll append it. I'll call toursBuffer.append and I'll pass in tour, plus a line feed. Finally, I'll wrap up the coding by going down to the call to displayText, and instead of outputting the rawBuffer, now I'll output the toursBuffer.

So, let's again review the code. I'm starting by using streams to read the content into memory. Then I'm deserializing from the string into a JSONArray object. Then I'm looping through the JSONArray and getting the data from the objects one at a time. And finally, I'm outputting the content that I've retrieved to the screen. I'll save and run the application in the emulator again. Remember, I've already created the file in persistent storage. I don't need to create it again.

I'll click Read file, and there's the result. I've retrieved the data, and I'm displaying it on the screen. So, that's a look at how you can both create files and read files using the JSON format. The JSON format is one of the smallest, most concise formats that you can use. It's incredibly fast on an Android device, and all the tools you need to use are included in the Android SDK.

There are currently no FAQs about Android SDK: Local Data Storage.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

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 Upgrade 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
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.

Are you sure you want to delete this note?

No

Notes cannot be added for locked videos.

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
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.