Android @ Kiowok

Shared Preferences

An easy and reliable way to save (and retrieve) application data is via SharedPreferences. SharedPreference data persists between runs of an application, and can be made private to the application or shared with other applications.

Saving Data

Setup your SharedPreference reference variable (usually as an instance variable):

SharedPreferences savedValues;

Then gain access to a SharedPreference object (often done in onCreate):

savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);

Save values:

Editor editor = savedValues.edit();
editor.putFloat("some_value", 39.5f); // store as a key/value pair
editor.putString("name", "susan");
editor.commit();

Retrieving Data

To retrieve the values, retrieve via the key under which the value was stored. Supply a default value in case a value cannot be retrieved:

int num = savedValues.getFloat("some_value", 0.0f); // 0.0f is supplied if "some_value" not found
String name = savedValues.getString("name", "NO NAME");

Default Preferences (Settings)

To get the default SharedPreference values:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Top