Sharedpreferences is the easiest to understand in Android data storage technology, in fact Sharedpreferences is dealing with a key-value (key-value pairs). Sharedpreferences is often used to store some lightweight data.
Copy Code code as follows:
Instantiate the Sharedpreferences object (first step)
Sharedpreferences mysharedpreferences= getsharedpreferences ("test"),
Activity.mode_private);
Instantiating the Sharedpreferences.editor object (step Two)
Sharedpreferences.editor Editor = Mysharedpreferences.edit ();
Saving 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 Message prompt box
Toast.maketext (This, "Data is successfully written to sharedpreferences! " ,
Toast.length_long). Show ();
By executing the above code, Sharedpreferences will save the data in a Test.xml file that can be exported and viewed under Data/data of File Explorer.
So how do you read the data that has been saved? We look at:
Copy Code code as follows:
[Code]
Similarly, to instantiate a Sharedpreferences object before reading the sharedpreferences data
sharedpreferencessharedpreferences= getsharedpreferences ("test"),
Activity.mode_private);
Get value using the GetString method, 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 balloon
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 Code code 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 is 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 ();
}
}
Figure 1.1 Program execution results