Sharedpreferences is the most understandable data storage technology in Android, and in fact sharedpreferences is dealing with a key-value (key-value pair) Sharedpreferences used to store some lightweight data Sharedpreferences is the most understandable data storage technology in Android, and in fact sharedpreferences is dealing with a key-value (key-value pair). Sharedpreferences is often used to store some lightweight data.
Instantiating a Sharedpreferences object (first step)
Sharedpreferences mysharedpreferences= getsharedpreferences ("Test",
Activity.mode_private);
Instantiating a Sharedpreferences.editor object (step Two)
Sharedpreferences.editor Editor = Mysharedpreferences.edit ();
Save the data in a putstring way
Editor.putstring ("name", "Karl");
Editor.putstring ("Habit", "sleep");
Submit Current Data
Editor.commit ();
To write data successfully using the TOAST information hint box
Toast.maketext (This, "data successfully written to sharedpreferences! " ,
Toast.length_long). Show ();
Executing the above code, Sharedpreferences will save the data in the Test.xml file, and you can export the file and view it under the Data/data of File Explorer.
So how do you read the data that has been stored? Let's see:
Copy CodeThe code is as follows:
[Code]
Similarly, an Sharedpreferences object is instantiated before reading sharedpreferences data
sharedpreferencessharedpreferences= getsharedpreferences ("Test",
Activity.mode_private);
Use the GetString method to get value, note that the 2nd parameter is the default value of value
String name =sharedpreferences.getstring ("name", "");
String habit =sharedpreferences.getstring ("Habit", "" ");
Display information using the Toast Information prompt box
Toast.maketext (This, "read the data as follows:" + "\ n" + "name:" + name + "\ n" + "habit:" + habit,
Toast.length_long). Show ();
The source code is as follows:
Copy CodeThe code is as follows:
public class Main extends Activity
{
@Override
public void OnCreate (Bundle savedinstancestate)
{
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
}
public void Onclick_writedata (view view)
{
Sharedpreferences mysharedpreferences = getsharedpreferences ("Test",
Activity.mode_private);
Sharedpreferences.editor Editor = Mysharedpreferences.edit ();
Editor.putstring ("name", "Karl");
Editor.putstring ("Habit", "sleep");
Editor.commit ();
Toast.maketext (This, "data successfully written to sharedpreferences! " ,
Toast.length_long). Show ();
}
public void Onclick_readdata (view view)
{
Sharedpreferences sharedpreferences = getsharedpreferences ("Test",
Activity.mode_private);
String name = sharedpreferences.getstring ("name", "");
String habit = sharedpreferences.getstring ("Habit", "" ");
Toast.maketext (This, "read the data as follows:" + "\ n" + "name:" + name + "\ n" + "habit:" + habit,
Toast.length_long). Show ();
}
}
Http://www.jb51.net/article/31911.htm
Android app Development sharedpreferences How to use stored data