Sharedpreferences is the easiest data storage technology to understand in Android, and in fact sharedpreferences is dealing with a key-value (key-value pair) Sharedpreferences 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 wayEditor.putstring ("name","Karl"); Editor.putstring ("Habit","Sleep");//Submit Current Dataeditor.commit ();//To write data successfully using the TOAST information hint boxToast.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:
//Similarly, an Sharedpreferences object is instantiated before reading sharedpreferences dataSharedpreferencessharedpreferences= Getsharedpreferences ("Test", activity.mode_private);//use the GetString method to get value, note that the 2nd parameter is the default value of valueString name =sharedpreferences.getstring ("name",""); String Habit=sharedpreferences.getstring ("Habit","");//display information using the Toast Information prompt boxToast.maketext ( This,"read the data as follows:"+"\ n"+"Name:"+ name +"\ n"+"habit:"+Habit,toast.length_long). Show ();
The source code is as follows:
Public classMain extends activity{@Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main);} Public voidonclick_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 voidonclick_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 ();}}
Android sharedpreferences Store Data