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).
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 variables 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) ; }
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here MyData is the name of XML file .It will be created automatically for you.
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 variables that I have used in MainActivity.