Always On, Always Connected Week 6 - Data Storage and Network Services

Data Storage

Android has several different ways that we can store data. We can use regular file storage, internal to our application or external (on the SD card). We can use SQLite Databases which require us to use SQL to structure the data or we can use a standard interface called SharedPreferences.

SharedPreferences

SharedPreferences is a standard data storage interface available in the Android API. It allows for the storage of key/value pairs in an file with a standard interface.

Save Data to SharedPreferences

SharedPreferences sharedPreferences = this.getSharedPreferences("sharedprefsname", MODE_PRIVATE);
SharedPreferences.Editor spe = sharedPreferences.edit();
spe.putString("name", "some value");
spe.commit();
		

Retrieve Data from SharedPreferences

SharedPreferences sharedPreferences = this.getSharedPreferences("sharedprefsname", MODE_PRIVATE);
String savedName = sharedPreferences.getString("name", "nothing");
		

JSON

JSON

JSON stands for JavaScript Object Notation. It has become a standard way to provide machine readable data to and from web services. Despite the fact that JavaScript is part of it's title, it is generally useful in all programming languages.

As stated on the json.org site: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

A simple JSON object
{
	fist_name: "Shawn",
	last_name: "Van Every
}		
		
An array of JSON objects
[
{
	fist_name: "Shawn",
	last_name: "Van Every"
},
{
	fist_name: "Joe",
	last_name: "Frank"
}		
]		
values can be string, number, null or boolean (true/false)

gson

You can parse JSON with Android using classes in the org.json package that comes with Android or you can use the Google gson library which is a lot easier.

The gson library will automatically parse the JSON data in to Java classes provided that you create the class that the data represents.

For instance to parse the above example JSON object, I would need a Java class that looked like this:
		
class Name
{
	public String first_name;
	public String last_name;
}
		
Then I could take a string of JSON and turn it into an object of that type:
String jsonString = "{\"first_name\": \"Joe\", \"last_name\": \"Frank\"}";
Gson gson = new Gson();
Name theName = gson.fromJson(jsonString, Name.class);
		
Now I have a Java Name object called theName that I can use normally.

Here is an example pulling JSON data from Flickr and displaying the images. This version doesn't use the gson library so it is a bit more verbose: FlickrJSONwLocation.zip

JSON in SharedPreferences

Using JSON in SharedPreferences gives us a nice way to store complex data.