Monday, 11 January 2016

Shared Preferences in Android

Shared Preferences is one of the storage method. By using this we can store the data in phone internal storage. when ever we need to store small/less size data then we can go for this concept.

--> We can access the SharedPreference data base using "getSharedPreferences" method. The following syntax is used to access the Shared Preference data.

SharedPreferences spf=activity.getSharedPreferences("Specify Your Own Database name",Context.MODE_PRIVATE);


---> If we need to do some modifications in above SharedPrefence, we can achieve with the help of   SharedPreferences.Editor


SharedPreferences.Editor spe=spf.edit();


--> We can insert a record using following syntax.

spe.putString("UserName", "Srikanth");
spe.putString("Password", "Patel");



Example for storing UserName and Password in SharedPreference.


/// Write the below code in Button Click to store Username and Password

public void storeData(View v)
{
    SharedPreferences spf=activity.getSharedPreferences("MyDataBase",Context.MODE_PRIVATE);
    SharedPreferences.Editor spe=spf.edit();
    spe.putString("UserName", "Srikanth");
    spe.putString("Password", "Patel");

    spe.commit();
}

// commit() returns true if the save works, false otherwise.



// this below code is used to read data from the shared Preference.

public void getData(View v)
{
    SharedPreferences spf=activity.getSharedPreferences("MyDataBase",Context.MODE_PRIVATE);
 
    String uname=spf.getString("UserName", "nodata");
    String pass=spf.getString("Password", "nodata");
   
}
 





No comments:

Post a Comment