Use of SharedPreferences in Android development,

Source: Internet
Author: User

Use of SharedPreferences in Android development,

InAndroidIn development, when storing a small amount of dataSharedPreferencesIs the best choice,SharedPreferencesStores data in key-value pairs.Boolean,Int,Float,Long,String

AndSet<String>The usage is as follows: declare in the class first:

Private SharedPreferences mSharedPreferences; // mEditor is used to edit SharedPreferencesprivate SharedPreferences. Editor mEditor;

InOnCreate ()Method:

MSharedPreferences = getPreferences (Context. MODE_PRIVATE); // The Editor object for obtaining SharedPreferences mEditor = mSharedPreferences. edit (); // Add a key-Value Pair mEditor whose name is "isFirstEnter" and whose value is false. putBoolean ("isFirstEnter", false); mEditor. putInt ("version", 1); mEditor. putFloat ("versionCode", 1.0f); mEditor. putLong ("long", 0); mEditor. putString ("string", "hello world"); Set <String> set = new HashSet <> (); set. add ("Tony"); set. add ("jack"); mEditor. putStringSet ("set <string>", set); // do not forget to submit mEditor after editing. commit ();

The above is a piece of stored data. What should I do if I want to read this data? The method is as follows:

/* The first parameter is the name of the saved key-value pair, and the second parameter is the default value. If you cannot find the key-value pair to be read, this method returns the default value you set, that is, true, or false. Set */mSharedPreferences as needed. getBoolean ("isFirstEnter", true)

Similarly, when reading data of other types, the corresponding * get * method is called. Is it easy to use?

PS: Develop a QR code application. You can try it if necessary ~ ^-^

 

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.