Friday, November 13, 2015

Android: Store values

We can save and load values, permanently, using Shared Preferences.

The shared preferences framework provides an easy way to store values, not only preference related but any kind of values. It's a file based so keep that in mind.

To get the SharedPreferences object we need:

private static final String NAME = "...";
public static SharedPreferences getPreferences(Activity a) {
  return a.getSharedPreferences(NAME , Context.MODE_PRIVATE);
}

To save a values we:

public static void save(Activity a) {
  SharedPreferences.Editor sp = getPreferences(a).edit();

  sp.putString("name1", value1);
  sp.putInt("name2", value2);

  sp.commit();
}

And to load a values we:

public static void load(Activity a) {
  SharedPreferences sp = getPreferences(a);

  value1 = sp.getString("name1", default1);
  value2 = sp.getInt("name2", default2);
}

We can also get a single Preferences for each activity with:

getPreferences(Context.MODE_PRIVATE)

Except MODE_PRIVATE we have MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE which are deprecated, so don't use them.


done_