Software Design and Development :: CS 246

09 Teach : Team Activity

Shared Preferences in Android

Objectives

Overview

This week you'll use the SharedPreferences system to store data that you want to persist between launches of your application, but that isn't large enough to require a database.

Instructions

The following steps will guide you through this process.

Part I - Plan what you need to store and store it.

  1. Brainstorm with your team the types of things you should be storing between sessions that aren't database-type items. For example, the user's profile name, the last screen they were looking at, their email address, their favorite number, etc...

    If you were previously thinking of using a database for local storage, consider whether using the shared preferences system, (possibly by serializing a class instance into JSON), would work just as well for your app, without the hassle of setting up a database.

  2. Write the code necessary to use SharedPreferences to store those items.

    You could wait until onPause() or onResume() is called, or you could save changes as they occur.

    Make sure you use best practices for your key names, by using static final strings, rather than "bare strings".

Part II - Write the code necessary to retrieve the data from Shared Preferences.

  1. Decide the best place to load the data you saved previously (likely in onCreate()).

  2. Load the data from shared preferences, and restore the application state as necessary.

    Don't forget to check that the data you're looking for was actually stored in SharedPreferences (which wouldn't be the case the first time the app is used, for example) and is valid (i.e. not null), before you attempt to use it for something.

Congratulations! You now know how to use SharedPreferences in your Android Project.

Make sure to complete the accompanying quiz for this assignment on I-Learn.