Here is a very simple implementation of Shared Preferences in Android Development.
Step 1: Create a Shared preferences object prefs from file “com.sagar.prefs”.
SharedPreferences prefs = getSharedPreferences(“com.sagar.prefs”, Context.MODE_PRIVATE );// this code is enough for creating the file and getting its object.
Step 2. Write some value in the shared preferences
copy this method in your code:
private void setPreferences(String key_str, String value_str){
Editor editor = prefs.edit();
editor.putString(key_str, value_str);
editor.commit();
}
and use this to save any value in shared preferences setPreferences(“name”, “value”); // this will save the value for this name.
Step 3: Get data from shared preferences:
String str = prefs.getString(“name”, “d”); // where d is the default value which will be return if there is no value for the given “name” in the shared preferences.
Filed under: Android Examples | Tagged: android, Android Example, Android source code, Shared preferences | Leave a comment »