Home > DeveloperSection > Interviews > Describe SharedPreference storage..

Posted on    June-01-2015 11:52 PM

 Android Android 
Ratings:
 1 Answer(s)
  375  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Points:4035
Posted on    June-01-2015 11:52 PM

SharedPreference is the simplest mechanism to store the data in android. You do not worry about creating the file or using files API.It stores the data in XML files. SharedPreference stores the data in key value pair.The SharedPreferences class allows you to save and retrieve key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: boolean, floats, int, longs, and strings.The data is stored in XML file in the directory data/data//shared-prefs folder.

Application of SharedPreference

  • Storing the information about number of visitors (counter).
  • Storing the date and time (when your Application is updated).
  • Storing the username and password.
  • Storing the user settings.

For storing the data
SharedPreferences sf=getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editored= sf.edit(); 
ed.putString("name", txtusername.getText().toString()); 
ed.putString("pass", txtpassword.getText().toString()); 
ed.commit();



In this example I have taken two activities. The first is MainActivity and the second one is SecondActivity.When user click on save button the user name and password that you have entered in textboxes, will be stored in MyData.xml file.

Here MyData is the name of XML file .It will be created automatically for you. 

MODE_PRIVATE means this file is used by your application only.

txtusernameand txtpassword are two EditText control in MainActivity.


For retrieving the data :

Public static final String DEFAULT=”N? A”;

DEFAULT is a String type user defined global variable.If the data is not saved in XML file and user click on load button then your application will not give the error. It will show message “No Data is found”. Here name and pass are same variable that I have used in MainActivity.

SharedPreferences sf=getSharedPreferences("MyData", Context.MODE_PRIVATE);
String Uname=sf.getString("name", DEFAULT);
String UPass=sf.getString("pass", DEFAULT);
if(name.equals(DEFAULT)||Pass.equals(DEFAULT)) 
{
Toast.makeText(this, "No data is found", Toast.LENGTH_LONG).show(); 
}
else
{
Txtusername.setText(Uname);
Txtpassword.setText(UPass) ;
}


Don't want to miss updates? Please click the below button!

Follow MindStick