How to Store Data in Shared Preference in Android

In this tutorial how to store data in Shared Preference in an Android Application is shown.

By using Shared Preference, we can store the data in pair of key & values.

By using Shared Preference, we can store the small collection of data.

A SharedPreference object points to a file containing key & value pairs and it provides a simple method to read and write.

The SharedPreference file is accessed by calling getSharedPreference() method and getPreference() method.

The getSharedPreference() method will access the multiple shared preferences where as getPreference() method will access only one shared preference.

It is widely used to get information from user such as in settings.

For ex. Synchronised Gmail Account.

Point to Remember:

  • If you want to see where your Application’s Shared Preferences are stored follow the below mentioned steps:
    1. Click the DDMS button on the top
    2. Open the File Explorer
    3. Open Data folder
    4. Again open the Data folder
    5. Open your package name folder, for ex. com.example.demo
    6. Open shared_prefs folder
    7. Your Shared Preferences are stored in the file present inside the  shared_prefs folder

Code:

activity_main.xml

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”.MainActivity” >

<TextView
android:id=”@+id/textPrefs”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_below=”@+id/showinfo”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”54dp” />

<TextView
android:id=”@+id/textView2″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignBottom=”@+id/storeinfo”
android:layout_centerHorizontal=”true”
android:layout_marginBottom=”78dp”
android:text=”Data Preference Example” />

<Button
android:id=”@+id/storeinfo”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentTop=”true”
android:layout_alignRight=”@+id/textView2″
android:layout_marginTop=”139dp”
android:text=”Store Information” />

<Button
android:id=”@+id/showinfo”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignRight=”@+id/storeinfo”
android:layout_below=”@+id/textView2″
android:layout_marginTop=”47dp”
android:text=”Show Information” />

</RelativeLayout>

res/xml/prefs.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<PreferenceScreen xmlns:android=”http://schemas.android.com/apk/res/android” >
<PreferenceCategory
android:summary=”Username and Password Information”
android:title=”Login Information”>
<EditTextPreference
android:key=”username”
android:summary=”Enter your username”
android:title=”Username”></EditTextPreference>
<EditTextPreference
android:key=”password”
android:summary=”Enter your password”
android:title=”Password”></EditTextPreference>
</PreferenceCategory>
<PreferenceCategory
android:summary=”Username and Password Information”
android:title=”Settings”>
<CheckBoxPreference
android:key=”checkBox”
android:summary=”On/Off”
android:title=”Keep me logged in”/>
<ListPreference
android:entries=”@array/listOptions”
android:entryValues=”@array/listValues”
android:key=”listpref”
android:summary=”List Preference Example”
android:title=”List Preference”/>
</PreferenceCategory>

</PreferenceScreen>

res/values/array.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
<string-array name=”listOptions”>
<item>English</item>
<item>French</item>
<item>German</item>
<item>Arabic</item>
<item>Hindi</item>
<item>Other</item>
</string-array>
<string-array name=”listValues”>
<item>English Language</item>
<item>French Language</item>
<item>German Language</item>
<item>Arabic Language</item>
<item>Hindi Language</item>
<item>Other Language</item>
</string-array>

</resources>

MainActivity.java

package com.example.demo;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity{

TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button storeinfo=(Button)findViewById(R.id.storeinfo);
Button showinfo=(Button)findViewById(R.id.showinfo);
tv=(TextView)findViewById(R.id.textPrefs);

View.OnClickListener listener=new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.storeinfo:
Intent intent=new Intent(MainActivity.this,PrefsActivity.class);
startActivity(intent);
break;
case R.id.showinfo:
displaySharedPreferences();
break;
default:
break;
}
}
};
storeinfo.setOnClickListener(listener);
showinfo.setOnClickListener(listener);
}

private void displaySharedPreferences(){
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String username=prefs.getString(“username”, “Default Username”);
String password=prefs.getString(“password”, “Default Password”);
boolean checkBox=prefs.getBoolean(“checkBox”, false);
String listPrefs=prefs.getString(“listpref”,”Default list prefs”);
StringBuilder builder=new StringBuilder();
builder.append(“Username: “+username+”\n”);
builder.append(“Password: “+password+”\n”);
builder.append(“Keep me logged in: “+String.valueOf(checkBox)+”\n”);
builder.append(“List Preference: “+listPrefs);
tv.setText(builder.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

PrefsActivity.java

package com.example.demo;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class PrefsActivity extends PreferenceActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}

}

AndroidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.example.demo”
android:versionCode=”1″
android:versionName=”1.0″ >

<uses-sdk
android:minSdkVersion=”8″
android:targetSdkVersion=”17″ />

<application
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
<activity
android:name=”com.example.demo.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>
<activity android:name=”.PrefsActivity”></activity>

</application>

</manifest>

Add a Comment

Your email address will not be published. Required fields are marked *