Android Tutorial on Shared Preferences

 

Android Shared Preferences :

Android Shared Preferences are used to store and retrieve data in between android activity’s  it is much helpful when data is to be used in more than one activity.

Shared Preferences is a light weight storage options we use mostly to save user credentials once logged in so that we can use this in remaining up screens.

Data is stored in key value pairs in shared preferences so we can make us of the key and retrieve the required value.We can store the data in terms of  String, int, float, boolean.

Shared preferences makes the data secured automatically by encrypting the keys using a encryption algorithm.

But make sure once the app is uninstalled the shared preferences are cleared up as well so use it for a light weight requirements for permanent storage use global storage options.

 

Initialization of a shared preference

 

 protected static final String AndroidCoding = null;
SharedPreferences.Editor editor = getSharedPreferences(AndroidCoding, MODE_PRIVATE).edit();

 

Here AndroidCoding String variable is used to store the values and the same is used in another activity to retrieve  Shared Preference can store and retrieve multiple types of data at once also, depending upon requirement we can use them i have listed out few types supported in shared preference.

 

  1. Boolean --> editor.putBoolean("key_name1", true);  
  2. Integer --> editor.putInt("key_name2", "int value"); 
  3. Float --> editor.putFloat("key_name3", "float value");
  4. Long --> editor.putLong("key_name4", "long value");
  5. String -->editor.putString("key_name5", "string value"); 

 

As it provides wide range of possibilities in storing data it is much helpful, and all the data is store at one place and can be used as many times as possible.

 

 

MainActivity.java

public class MainActivity extends Activity {

	protected static final String AndroidCoding= null;
	Button savebtn;
	EditText editText;
	String getText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		savebtn = (Button)findViewById(R.id.savebtn);
		editText = (EditText)findViewById(R.id.editText);

		savebtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

            	getText =  editText.getText().toString();

            	SharedPreferences.Editor editor = getSharedPreferences(AndroidCoding, MODE_PRIVATE).edit();
            	 editor.putString("AC", getText);
            	 editor.commit();

            	 Intent i = new Intent(MainActivity.this,Second_Screen.class);
             	startActivity(i);

            }
            });


	}

 

 

  Adding edittext, textview and button for user to input text

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.androidcoding.abhi.shared_preferences.MainActivity" >

    <TextView
        android:id="@+id/texttitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:layout_gravity="center"
        android:text="Main Screen"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="enter text here..."
        android:background="#ffffff"
        android:layout_marginTop="60dp" >

    </EditText>

    <Button
        android:id="@+id/savebtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save and go to next screen"
        android:layout_marginTop="50dp" />

</LinearLayout>

 

 

Now we will be creating second screen where we will fetch the shared preference value and show it with help of a text-view.

Second_Screen.java

public class Second_Screen extends Activity {

	private static final String AndroidCoding = null;
	Button backbtn;
	TextView textView;
	String setText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.secondscreen);

		backbtn = (Button)findViewById(R.id.backbtn);
		textView = (TextView)findViewById(R.id.textView);

		SharedPreferences prefs = getSharedPreferences(AndroidCoding, MODE_PRIVATE);
		setText = prefs.getString("AC", "nothing/no value");

		textView.setText(setText);

		backbtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

            	Intent i = new Intent(Second_Screen.this,MainActivity.class);
            	startActivity(i);

            }
            });

	}

 

 

 secondscreen.xml :

Now we will design second screen to show output

 

<?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:orientation="vertical" >


      <TextView
        android:id="@+id/texttitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:layout_gravity="center"
        android:text="Second Screen"
        android:textAppearance="?android:attr/textAppearanceLarge" />

      <TextView
          android:id="@+id/textView"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:text="TextView"
          android:layout_marginTop="60dp" />


    <Button
        android:id="@+id/backbtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Back"
        android:layout_marginTop="50dp" />

</LinearLayout>

 

 

AndroidManifest.xml

  Adding Second_Screen.java to manifest file and no special permissions are required.

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidcoding.abhi.shared_preferences"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidcoding.abhi.shared_preferences.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="com.androidcoding.abhi.shared_preferences.Second_Screen"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>




 

Android Shared Preferences Output :

The screen depicts the implementation of android shared preferences.

  Android Shared Preferences

That’s it for this tutorial any queries on Android Shared Preferences let us know in comment section below.

For more interesting tutorials do like and share this tutorial.

 

Show Buttons
Hide Buttons
Read previous post:
Android Gridview Made Easy: A Beginner’s Tutorial

  Android Gridview : Android Gridview is generally used to  represent data in form of grids, i.e., rows and columns, in...

Close