Describe SharedPreference storage option with example.
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.
Example:For storing the data we will write the following code in main activity on save button:
SharedPreferences sf=getSharedPreferences("MyData", MODE_PRIVATE);
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 we will write the following code in SecondActiviy when user click on Load button:
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);
Toast.makeText(this, "No data is found", Toast.LENGTH_LONG).show();