Android Tip: Preferences - Easier Than Using a Database - With Code Sample!

Attached File(s): 

If you have done any programming for an Android phone, you've probably already used (or at least heard of) Android's built-in database option of SQLite.  SQLite is a fine system, but it can be cumbersome to work with, especially if you only need to store a few values. 

samsung-omnia-hd-android.jpgEnter your new best friend: Preferences.

Think of "Preferences" as a way to save data (like Strings) outside of your application.  It's like a database in that way, but it is much easier to put data in and get data out.  If you build a Preferences Activity at some point, then it will actually be using this very system-- but that's another blog post.

I have included my own class for working with Preferences.  It is linked at the top of the post.  To use it, instantiate a Prefs object like so:

Prefs prefs = new Prefs(context);
// Prefs prefs = new Prefs(this) will work 
// if you are within an Activity

Now, to store a String value, all you have to do is this:

String mUserNameString = "rpeacock";
prefs.setPreference("username", mUserNameString);

To retrieve that value later, even after the app has closed and restarted, all you have to do is this:

String temp = prefs.getPreference("username");

Isn't that easy?  More to the point, isn't that much easier than creating an SQLite object, constructing a query, executing the query, then closing the connection?  That's why I use Preferences everywhere I can.  It's also great for accessing values between Activities, services, etc.

The code I attached only does Strings, but you can easily extend it to work with any value.  Enjoy!

 


Software License Fine Print

Creative Commons LicenseThis code is licensed as-is, with no warranty or guarantee, under a Creative Commons Attribution 3.0 Unported License.

You may use this code however you want, even in commercial products, but only if you include attribution to me, Richard Peacock, as the original author of this small portion of code, but not in a way that implies I endorse your project.

For example, on a Help/Credits screen:  Portions of this project were based on work freely obtained from these developers: Richard Peacock (http://richardpeacock.com), NAME HERE, etc.  These outside developers neither endorse nor support this software.

If you use this code, feel free to email me to let me know!  I'll include a link to your project here.

Can I have Hidden fields in

Can I have Hidden fields in Preferences. they should not be visible to the user but app should be able to read & write values to those fields.

Sure, that's exactly what I

Sure, that's exactly what I am describing in the post. Instead of setting up a preferences activity, you just access them directly, like a database.