Android app Development sharedpreferences How to use stored data

Source: Internet
Author: User

Android app Development sharedpreferences How to use stored data

Sharedpreferences is the most understandable data storage technology in Android, in fact Sharedpreferences is dealing with a key-value (key-value pair) sharedpreferences commonly used to save to store some lightweight data.

1, the use of sharedpreferences to save data methods are as follows :

//Instantiate Sharedpreferences object (first step)
sharedpreferences mysharedpreferences= getsharedpreferences ("Test",
activity.mode_private);
//Instantiate Sharedpreferences.editor object (step two)
Sharedpreferences.editor Editor = Mysharedpreferences.edit ();
//Save data with Putstring method
editor.putstring ("name", "Karl");
editor.putstring ("Habit", "sleep");
//Submit Current Data
Editor.commit ();
//Use the TOAST information hint box to prompt to write data successfully
Toast.maketext (This, "data successfully written to sharedpreferences! " , Toast.length_long). Show ();


Execute the above code, Sharedpreferences will save this data in the Test.xml file, you can export it under the data/data/corresponding package name/test.xml of the File explorer and view it.



2, the use of Sharedpreferences read data method as follows :


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 ();




Android app Development sharedpreferences How to use stored data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.