Android SharedPreferences
Android SharedPreferences
Android SharedPreferences allows users to save and retrieve specific data of an application in the form of key,value pair. In general, Android SharedPreferences is used to save small collection of key-values. In order to use shared preferences, you have to call getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences. Each SharedPreferences file is managed by the framework and can be private or shared.
Preferences can be permanently stored using Android SharedPreferences in the form of a pair : key and a value, primitive data storage (boolean Strings, ints etc..). If you uninstall the application, all your data will be lost, hence this is application specific. It is added in API Level 1. The data will be stored at
data/data/package name/shared_prefs.
Now, lets take a look at how to use Android SharedPreferences class to store and retrieve application specific persistent data.
Open DDMS->File Explorer.
Available mode for shared preference
1. MODE_WORLD_READABLE
2. MODE_WORLD_WRITEABLE
3. MODE_PRIVATE
Create SharedPreferences:
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Or using PreferenceManager
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(context);
Storing data as KEY/VALUE pair:
Editor editor = pref.edit();
editor.putBoolean("key1", true); // Saving boolean - true/false
editor.putInt("key2", "int value"); // Saving integer
editor.putFloat("key3", "float value"); // Saving float
editor.putLong("key4", "long value"); // Saving long
editor.putString("key5", "string value"); // Saving string
// Save the changes in SharedPreferences
editor.commit(); // commit changes
Get SharedPreferences data:
// If value for key not exist then returns value null
prefs.getBoolean("key1", null); // getting boolean
prefs.getInt("key2", null); // getting Integer
prefs.getFloat("key3", null); // getting Float
prefs.getLong("key4", null); // getting Long
prefs.getString("key5", null); // getting String
Deleting Key value from SharedPreferences:
editor.remove("key1"); // will delete key key_name3
editor.remove("key2"); // will delete key key_name4
// Save the changes in SharedPreferences
editor.commit(); // commit changes
Clear all data from SharedPreferences:
editor.clear();
editor.commit(); // commit changes
Ex:
Create MainActivity.java under src/<your packagename>.
MainActivity.java:
[java]
public class MainActivity extends Activity {
Context context;
SharedPreferences prefs;
private String TEXT="text";
String key;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save=(Button)findViewById(R.id.button1);
Button show=(Button)findViewById(R.id.button2);
final EditText text=(EditText)findViewById(R.id.editText1);
final TextView dText=(TextView)findViewById(R.id.textView1);
context=this;
prefs=PreferenceManager.getDefaultSharedPreferences(context);
//on click save
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editor edit=prefs.edit();
edit.putString(TEXT, text.getText().toString());
edit.commit();
}
});
//on click show
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
key=prefs.getString(TEXT, null);
dText.setText(key);
}
});
}
}
[/java]
Create activity_main.xml under res/layout folder.
activity_main.xml:
[code lang="xml"]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#FFFFFF"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#009ACD"
android:layout_marginTop="30dp"
android:text="Save" >
</Button>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#009ACD"
android:text="Show" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="" />
</LinearLayout>
[/code]
AndroidManifest.xml:
[code lang="xml"]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spl.myproject"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.spl.myproject.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
[/code]
Output: