Storing preferences
One of the easiest ways to store information from our application is to store application preferences. Android provides us with a class named SharedPreferences
to do this; however, it can be used to store anything that can be represented by a key-value. Refer to http://developer.android.com/reference/android/content/SharedPreferences.html for more information.
Initialization
To use the SharedPreferences
class, we have to get a reference to a preferences file. To do this, we can simply use the getSharedPreferences(String name, int mode)
method in our context; refer to
http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String, int). Alternatively, if we only need one single preference file, we can always use getPreferences(int mode)
from our activity.
Context.getPreferences
will internally call getSharedPreferences
and use the class name of the activity as the filename.
There are three different modes to get the preferences...