Sharedpreferences is the most understandable data storage technology in Android. In fact, sharedpreferences process a key-value pair ). Sharedpreferences is often used to store lightweight data.
CopyCode The Code is as follows: // instantiate the sharedpreferences object (step 1)
Sharedpreferences mysharedpreferences = getsharedpreferences ("test ",
Activity. mode_private );
// Instantiate the sharedpreferences. Editor object (step 2)
Sharedpreferences. Editor editor = mysharedpreferences. Edit ();
// Use putstring to save data
Editor. putstring ("name", "Karl ");
Editor. putstring ("habit", "Sleep ");
// Submit the current data
Editor. Commit ();
// Use the toast prompt box to prompt that data is successfully written.
Toast. maketext (this, "data is successfully written to sharedpreferences! ",
Toast. length_long). Show ();
Run the above Code. sharedpreferences will save the data in the test. xml file. You can export and view the file under data/data of file explorer.
How can we read the saved data. Let's take a look:Copy codeThe Code is as follows: [Code]
// Similarly, a sharedpreferences object needs to be made into an instance before reading sharedpreferences data
Sharedpreferencessharedpreferences = getsharedpreferences ("test ",
Activity. mode_private );
// Use the getstring method to obtain the value. Note that the first parameter is the default value of the value.
String name = sharedpreferences. getstring ("name ","");
String habit = sharedpreferences. getstring ("habit ","");
// Use the toast prompt box to display information
Toast. maketext (this, "read data is as follows:" + "\ n" + "name:" + name + "\ n" + "habit:" + habit,
Toast. length_long). Show ();
Source codeAs 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)
{
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)
{
Sharedpreferences = getsharedpreferences ("test ",
Activity. mode_private );
String name = sharedpreferences. getstring ("name ","");
String habit = sharedpreferences. getstring ("habit ","");
Toast. maketext (this, "read data is as follows:" + "\ n" + "name:" + name + "\ n" + "habit:" + habit,
Toast. length_long). Show ();
}
}
Fig 1.1ProgramExecution result