Android SharedPreference





Android SharedPreference



  • Store / Insert Values from Android to SharedPreferences.

  • Retrive / Select Values from SharedPreferences to Android.

  • Update Values from Android to SharedPreferences.

  • Clear / Delete Values from SharedPreferences.




Store / Insert Values from Android to SharedPreferences.

Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.


Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="36dp"
        android:padding="11dp"
        android:hint="Id"
        android:ems="10"
        android:inputType="number">

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:padding="11dp"
        android:hint="Name"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp"
        android:padding="11dp"
        android:text="Save" />

</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :


package com.gudivada.hemanthsomaraju;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private SharedPreferences prefs;
    private String prefName = "report";
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        final EditText e_id=(EditText) findViewById(R.id.editText1);
        final EditText e_name=(EditText) findViewById(R.id.editText2);
        Button save=(Button) findViewById(R.id.button1);
       
        save.setOnClickListener(new View.OnClickListener() {
           
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               
           
            String s1=e_id.getText().toString().trim();
            String s2=e_name.getText().toString().trim();
            if(s1.length()<=0)
            {
                Toast.makeText(getApplicationContext(), "please enter id", Toast.LENGTH_SHORT).show();
                e_id.requestFocus();
            }
            else
                if(s2.length()<=0)
                {
                    Toast.makeText(getApplicationContext(), "please enter name", Toast.LENGTH_SHORT).show();
                    e_name.requestFocus();
                }
                else
           
           
                {
           
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
       
                //---save the values in the EditText view to preferences---
            editor.putInt("id", Integer.parseInt(e_id.getText().toString()));
                editor.putString("name", e_name.getText().toString());
       
                //---saves the values---
                    editor.commit();
       
                Toast.makeText(getBaseContext(), "Saved",
                Toast.LENGTH_SHORT).show();
        }
    }});       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }   
}


Step 4 : Open AndroidManifest.xml and add following code :

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

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

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



Step 5 : Our output will be like this :








Retrive / Select Values from SharedPreferences to Android.

Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.


Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:hint="Id"
        android:padding="11dp"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:hint="Name"
        android:padding="11dp"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:padding="11dp"
        android:text="Save" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"       
    android:layout_centerVertical="true"
    android:padding="11dp"
        android:text="Select" />

</RelativeLayout>


Step 3 : Open src -> package -> MainActivity.java and add following code : 
 
package com.gudivada.hemanthsomaraju;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
   
    private SharedPreferences prefs;
    private String prefName = "report";
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        final EditText e_id=(EditText) findViewById(R.id.editText1);
        final EditText e_name=(EditText) findViewById(R.id.editText2);
        Button save=(Button) findViewById(R.id.button1);
        Button select=(Button) findViewById(R.id.button2);
       
        save.setOnClickListener(new View.OnClickListener() {
          
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
              
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
       
                //---save the values in the EditText view to preferences---
            editor.putInt("id", Integer.parseInt(e_id.getText().toString()));
            editor.putString("name", e_name.getText().toString());
       
                //---saves the values---
                    editor.commit();
       
                Toast.makeText(getBaseContext(), "Saved",
                Toast.LENGTH_SHORT).show();
        }
    });
       
        select.setOnClickListener(new View.OnClickListener() {
          
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
              
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
          
                Toast.makeText(getBaseContext(), String.valueOf(prefs.getInt
                ("id", 523)), Toast.LENGTH_SHORT).show();
                   Toast.makeText(getBaseContext(), prefs.getString
                ("name", "Hemanth Somaraju"), Toast.LENGTH_SHORT).show();
        }
    });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
 
 
Step 4 : Open AndroidManifest.xml and add following code :



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

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

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



Step 5 : Our output will be like this :










Update Values from Android to SharedPreferences.

Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.


Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :
 
<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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:hint="Id"
        android:padding="11dp"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:hint="Name"
        android:padding="11dp"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:padding="11dp"
        android:text="Save" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"       
    android:layout_below="@+id/button1"
    android:layout_marginTop="20dp"
    android:padding="11dp"
        android:text="Select" />
   
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"       
    android:layout_below="@+id/button2"
    android:layout_marginTop="20dp"
    android:padding="11dp"
        android:text="Update" />

</RelativeLayout>
 
Step 3 : Open src -> package -> MainActivity.java and add following code :
 
package com.gudivada.hemanthsomaraju;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private SharedPreferences prefs;
    private String prefName = "report";
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        final EditText e_id=(EditText) findViewById(R.id.editText1);
        final EditText e_name=(EditText) findViewById(R.id.editText2);
        Button save=(Button) findViewById(R.id.button1);
        Button select=(Button) findViewById(R.id.button2);
        Button update=(Button) findViewById(R.id.button3);
       
        save.setOnClickListener(new View.OnClickListener() {
           
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
       
                //---save the values in the EditText view to preferences---
            editor.putInt("id", Integer.parseInt(e_id.getText().toString()));
                editor.putString("name", e_name.getText().toString());
       
                //---saves the values---
                    editor.commit();
       
                Toast.makeText(getBaseContext(), "Saved",
                Toast.LENGTH_SHORT).show();
        }
    });
       
        select.setOnClickListener(new View.OnClickListener() {
           
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
           
                Toast.makeText(getBaseContext(), String.valueOf(prefs.getInt
                ("id", 523)), Toast.LENGTH_SHORT).show();
                Toast.makeText(getBaseContext(), prefs.getString
                ("name", "Hemanth Somaraju"), Toast.LENGTH_SHORT).show();
        }
    });
       
        update.setOnClickListener(new View.OnClickListener() {
           
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
       
                //---save the values in the EditText view to preferences---
            editor.putInt("id", Integer.parseInt(e_id.getText().toString()));
                  editor.putString("name", e_name.getText().toString());
       
                //---saves and update the values both are same---
                    editor.commit();
       
                Toast.makeText(getBaseContext(), "Updated Successfully",
                Toast.LENGTH_SHORT).show();
        }
    });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }   
}


Step 4 : Open AndroidManifest.xml and add following code :


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

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

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


Step 5 : Our output will be like this :











Clear / Delete Values from SharedPreferences.


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.


Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:hint="Id"
        android:padding="11dp"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:hint="Name"
        android:padding="11dp"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:padding="11dp"
        android:text="Save" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"       
    android:layout_below="@+id/button1"
    android:layout_marginTop="20dp"
    android:padding="11dp"
        android:text="Select" />
   
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"       
    android:layout_below="@+id/button2"
    android:layout_marginTop="20dp"
    android:padding="11dp"
        android:text="Update" />
   
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"       
    android:layout_below="@+id/button3"
    android:layout_marginTop="20dp"
    android:padding="11dp"
        android:text="Clear" />
   

</RelativeLayout>


Step 3 : Open src -> package -> MainActivity.java and add following code :


package com.gudivada.hemanthsomaraju;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


    private SharedPreferences prefs;
    private String prefName = "report";
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        final EditText e_id=(EditText) findViewById(R.id.editText1);
        final EditText e_name=(EditText) findViewById(R.id.editText2);
        Button save=(Button) findViewById(R.id.button1);
        Button select=(Button) findViewById(R.id.button2);
        Button update=(Button) findViewById(R.id.button3);
        Button clear=(Button) findViewById(R.id.button4);
       
        save.setOnClickListener(new View.OnClickListener() {
           
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
       
                //---save the values in the EditText view to preferences---
            editor.putInt("id", Integer.parseInt(e_id.getText().toString()));
                   editor.putString("name", e_name.getText().toString());
       
                //---saves the values---
                    editor.commit();
       
                Toast.makeText(getBaseContext(), "Saved",
                Toast.LENGTH_SHORT).show();
        }
    });
       
        select.setOnClickListener(new View.OnClickListener() {
           
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
           
                Toast.makeText(getBaseContext(), String.valueOf(prefs.getInt
                ("id", 523)), Toast.LENGTH_SHORT).show();
                Toast.makeText(getBaseContext(), prefs.getString
                ("name", "Hemanth Somaraju"), Toast.LENGTH_SHORT).show();
        }
    });
       
        update.setOnClickListener(new View.OnClickListener() {
           
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
       
                //---save the values in the EditText view to preferences---
            editor.putInt("id", Integer.parseInt(e_id.getText().toString()));
                 editor.putString("name", e_name.getText().toString());
       
                //---saves and update the values both are same---
                    editor.commit();
       
                Toast.makeText(getBaseContext(), "Updated Successfully",
                Toast.LENGTH_SHORT).show();
        }
    });
       
        clear.setOnClickListener(new View.OnClickListener() {
           
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               
            prefs = getSharedPreferences(prefName, MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
       
            editor.clear();
            editor.commit();
        }
    });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }   
}



Step 4 : Open AndroidManifest.xml and add following code :

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

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

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


Step 5 : Our output will be like this :