Saving Data

Beginning Android Development Part 6 - Saving Data

Written by
Published on
Modified on

It's hard nowadays to find a website or Windows application that doesn't make use of a database in some way. Android apps are no exception. Android offers several ways to store user data, or application data each with it's own pros and cons and use scenarios. You can store small bits of data into key/value pairs into a SharedPreferences file, or files. You can store your data into files, great for larger amounts of data or images. And lastly you can use a database, if you require organized data that needs to queryable. This isn't the most exciting topic, but again, the basics will help save time when the real work starts.

Key Value Pairs (Shared Preferences)

The simplest way to store data into your Android application is to use SharedPreferences. A SharedPreference points to a file on your system that houses a series of key-value pairs that you define for your application. If you wish, you can have multiple SharedPreference files each with their own individual name, or only a single one for your application. You can create and or grab a SharedPreferences instance by calling getPreferences() with its protection level passed in.

// get single use preferences
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);

Grab or create a single SharedPreference file

You can also have multiple Shared Preference files per project by using getSharedPreferences() instead of getPreferences(). getSharedPreferences takes in the file name as its first parameter.

       SharedPreferences sharedPref = getSharedPreferences(
       getString(R.string.preference_file_key), Context.MODE_PRIVATE);

Name SharedPreference with the name being a string resource

We set the context mode to MODE_PRIVATE, so that only our application has access to read and write to the file. However, we can also set it to MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE, then any other apps that know the file identifier can access your data.

Write To A Shared Preference

That's how we create or grab a shared preference file, now let's add some data to it.

        // get single use preferences
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(getString(R.string.saved_high_score), 3555);

In order to write to the system created lonely file, we need to create an object of the SharedPreferences.Editor type, which we get by calling the edit() method in our SharedPreferences object. We can then call putInt or putString in order to add our data to the object, depending on the type of data that we are working with, and seal the deal with commit().

Read From A Shared Preference

In order to read from a SharedPreference, we can call getInt() or getString() on our SharedPreferences object. The getInt() method takes in the name of the preference to grab, and a default value, if that preference is not set.

       SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
       int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
       long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

Testing It Out With DDMS

So how do we know that this worked? I sure didn't the first time I did it. I looked around for the key/value file, but had no look. And that's of course because I was looking at the projects physical files, and not the emulators virtual directory, which we can do.

The Android SDK ships with DDMS or Dalvik Debug Monitor Server, very awesome name, I know. The tool gives tons of extra information about your application as it's running, from screen capture to thread and heap information and what we need, a file explorer.

It is built in to Eclipse, which is what I'm using and to get to it, we first need to enable it to show in our menu panel. Click on Window->Open Perspective->Other... to get a listing of all possible windows to show.

You should now see the DDMS tab icon on the top right of the IDE. Click on it now, and you'll see nothing much. Run the emulator though, and that's where the fun begins. You can do all kinds of things with this tool, such as spoof phone calls and play around with signal speed if that is what you so desire. Very cool little testing tool.

For our case, let's head on over to the File Explorere tab and dropdown to data/data/packagename/shared_prefs and we'll see our file with our SharedPreferences data. I couldn't open the file, for some reason, but at least it's there, and after adding a few more pieces of data and seeing the file size increase, I'll stop there and call it a success.

That took longer than I thought, so I will skip the File Saving portion until the next post. But at least for now, you and, I equally, have learned to store key/value pairs within the Android Framework and how to retrieve them. Just a recap, Grab an instance of SharedPreferences class, whether for single file or multiple, create an Editor object to write to the file, and call the putInt/putString methods to write and getInt/getString methods to retrieve the data. Happy coding.


No messages posted yet

Developer Poll


Add a comment

Send me your weekly newsletter filled with awesome ideas