Wednesday, 3 October 2012

Android Shared Preferences Tutorial


Shared Preferences
                       
                        Shared Preferences store small amount of data and it is private to your application.The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use Shared Preferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

Basically there are two methods for Shared Preferences:
         
         Use this if you need multiple preferences files identified by name, which you specify with the first parameter.What ever file name you are giving in getSharedPerferences(),the file will create the same name of xml file.

     2.    getPreferences(<mode>)
  
         Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name. Here we are not passing any file name, your file name automatically taken as ActivityName.xml.

Creating and Writing into Shared Preferences File:

            1.    Get the Editor
                SharedPreferences.Editor e = s.edit();
            2.    Modify the Editor
                e.putBoolean(<VariableName>,<Value>);
      3. Save the Editor
                  e.commit();



Let’s See the Program:

SharedPerferencesTestActivity.java

public class SharedPerferencesTestActivity extends Activity
{
            //Preference File Name
            public static final String MY_PREF = "MyPreferences";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final Button btn = (Button)findViewById(R.id.button1);
        final Intent it = new Intent(getApplicationContext(), TargetActivity.class);
       
        //Creating Instance of SharedPreferences
        SharedPreferences sp = getSharedPreferences(MY_PREF, 0);
       
        //Getting the Editor
        SharedPreferences.Editor edit = sp.edit();
       
        //Modifying Editor
        edit.putInt("No of Item", 3);
        edit.putString("item1", "One");
        edit.putString("item2", "Two");
        edit.putString("item3", "Three");
       
        //Save the Editor value
        edit.commit();
       
        btn.setOnClickListener(new OnClickListener() {
                                   
                                    @Override
                                    public void onClick(View v)
                                    {
                                                startActivity(it);
                                    }
                        });
    }
}


TargetActivity.java

public class TargetActivity extends Activity
{
                @Override
                protected void onCreate(Bundle savedInstanceState)
                {
                                super.onCreate(savedInstanceState);
                               
                                //Reading the Preferences File
                                SharedPreferences s = getSharedPreferences(SharedPerferencesTestActivity.MY_PREF, 0);
                                int i = s.getInt("No of Item", 0);
                               
                                if(i>0)
                                {
                                                String item1 = s.getString("item1", "");
                                                Toast.makeText(getApplicationContext(), item1, 0).show();
                                               
                                                String item2 = s.getString("item2", "");
                                                Toast.makeText(getApplicationContext(), item2, 0).show();
                                               
                                                String item3 = s.getString("item3", "");
                                                Toast.makeText(getApplicationContext(), item3, 0).show();
                                }
                }

}

Result:
            >>When you click on the Button, Shared Preferences will read the values what ever you have store in xml file.
You can also Check that xml file created or not. For that you need to follow bellow steps:
Go to Window-> ShowView -> File Explorer(Click on It)
Now Go to DDMS -> Click your Device Name(Which is Running Currently) -> Click on File Explorer -> data -> data -> Choose Your Package name(Ex.  Com.shared) -> Under that package you can See your Preferences File Name.







3 comments:

  1. Good work.............also get a detail tutorial with sample project at......http://androidtutorialsrkt.blogspot.in/

    ReplyDelete
  2. Watch the Video and get the free raw code:

    https://www.youtube.com/watch?v=sV91zVC4IxM

    ReplyDelete