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 ~ ^-^