SharedPreferences data storage function
This is a lightweight storage class. In fact, SharedPreferences processes a key-value (key-value Pair) SharedPreferences, which is often used to store lightweight data. Let's talk about how it operates today. We know that this storage class can only be used in the same package class (similar to the global variable of an application ). Its storage location is in/data/ <包名> /Shared_prefs directory. The SharedPreferences object can only obtain data, but does not support storage and modification. The storage modification is implemented through the Editor object. The procedure is as follows:
1. Get the SharedPreferences object based on Context (generally, you can directly call getSharedPreferences () in the onCreate method, or use Context ctx = Class Name. this ;)
2. Use the edit () method to obtain the Editor object (generally, the SharedPreferences object obtains data, but the Editor object needs to be obtained for data storage ).
3. Use the Editor object to store key-value pairs. PutXXX (key, value) is used for storage.
4. submit data using the commit () method. If this step is not performed, the data will not be saved to the xml file.
Example:
Publicclass MainActivity extends Activity {
@ Override
Publicvoid onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Obtain the SharedPreferences object
Context ctx = MainActivity. this;
SharedPreferences sp = ctx. getSharedPreferences ("test", MODE_PRIVATE );
// Store data
Editor editor = sp. edit ();
Editor. putString ("name", "zhangsan ");
Editor. putInt ("id", 1 );
Editor. commit ();
}
}
How can I get the data after it is saved? The steps are similar to those above, but the Editor object is missing.
Example:
// Obtain the SharedPreferences object
Context ctx = MainActivity. this;
SharedPreferences sp = ctx. getSharedPreferences ("test", MODE_PRIVATE );
// Returns the STRING_KEY value.
// If NOT_EXIST does not exist, the returned value is "none"
Log. d ("test", sp. getString ("name", "none "));
Log. d ("test", sp. getInt ("id", 0 ));