Storing data across multiple application sessions is important. To enable the application to persist data , there are many options available but here we going to discuss just two methods. SharedPreferences is used to store small pieces of key-value pairs while the SQLite database is used to persist complex data. Let's first see how to store and access data from SharedPreferences.
SharedPreferences:
Remember that the sharedPreferences is retrieved with the current activity as the name when calling getPreferences(MODE_PRIVATE);. You could also save preferences with custom name by fetching sharedPreferences as follows.
getSharedPreferences('GeoPref', mode);
If a SharedPreference named GeoPref is not present then a new one is created and returned.
Storing data
1. Get reference to SharedPreference from an activity using the following code.
final SharedPreferences prefs = getPreferences(MODE_PRIVATE);
This will call the getSharedPreferences('currentActivityName', mode) method of the context object.
2. Store key, value into the map using the following code
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("HIGH_SCORE", val);
editor.commit();
Read data
Just call prefs.getInt("HIGH_SCORE", -2). If such a key is not present then the passed -2 is returned.
SharedPreferencesFragment
This class is useful for presenting a list view of needed preferences to be saved for an application. It is very useful when showing, editing by displaying a dialog and saving multiple settings for an application with just few lines of code.
1. Load the fragment just like a normal fragment by defining it in xml or by calling it dynamically
setContentView(R.layout.user_prefs_fragment);
The user_prefs_fragment xml is shown below.
Note that you can reference an inner class in xml using the symbol '$'
2. Load the preference and register the change listener for setting the initial value of uname as shown below
The xml from which the items to be loaded on to the fragment is defined in R.xml.user_prefs as shown below
The above file helps to display a dialog box to accept changes when a particular key-value is edited. This is what makes SharedFragment so easy to view and edit existing preferences.
Initially there is no value set for the uname key . So the changeListener is called back by invoking onSharedPreferenceChanged as shown below.