Android study note 35: using shared preferences to store data

Source: Internet
Author: User

Android provides five data storage methods:

(1) files: Use fileinputstream and fileoutputstream to operate files. For details about how to use it, refer to the blog "android study note 34: Using files to store data".

(2) shared preferences: used to store data in the form of key-value pairs and save system configuration information.

(3) content providers: data sharing for ApplicationsProgramData access.

(4) SQLite: a lightweight relational database built in Android that supports the SQL language. It is used to store a large amount of data and can be used, updated, maintained, and operated on the data.

(5) Network: stores and obtains data through the network.

This blog article mainly introduces the second method to store data through shared preferences.

 

1. Use shared preferences to store and read data

Shared preferences is a lightweight storage class provided by the Android system. It is mainly used to save some configuration information, such as window status (size and brightness ).

Shared preferences uses key-value pairs to store data. Common data types such as Boolean, float, Int, long, and string can be saved. The stored data is stored in the/data/<package name>/shared_prefs directory as an XML file.

1.1 Use shared preferences to store data

You can use the following four steps to use shared preferences to store data: (1) Use the getsharedpreferences () method provided by the context class to obtain the sharedpreferences object. The following is a prototype of the getsharedpreferences () method:

Public abstract sharedpreferences getsharedpreferences (string name, int mode );

The parameter name indicates the name of the file storing the data. Note that the file name is defined here. The file is not actually created, and only when sharedpreferences is created. when you edit an object and submit data using the Commit () method of the object, the object is created.

The mode parameter is used to specify the file operation mode. The optional values include context. mode_append (content appending mode), context. mode_private (default operation mode), context. mode_world_readable (readable mode), context. mode_world_writeable (writable mode) is the same as the second parameter of the openfileoutput () method mentioned in "android study note 34: using file storage data.

(2) Use the Edit () method of the sharedpreferences object to create the sharedpreferences. Edit object. When using shared preferences to store data, you must use the sharedpreferences. Edit class to add data. The sharedpreferences. Edit class provides method 1.

Figure 1 methods provided by the sharedpreferences. Edit class

It can be seen that the sharedpreferences. Edit class provides a key-value pair to store Boolean, float, Int, long, and string data types.

(3) Use the sharedpreferences. Edit object to store data.

(4) use the Commit () method to submit data.

A simple example of how to store data through the above four steps is as follows:

 1       /*  2   * Function: Save the data to the sharedpreferences object.  3   * Param: name of the file in which the filename is used to store the data. username and userpswd are used to store the data.  4   * Author: blog Park-still indifferent  5        */  6      Public   Boolean Savedatatosharedpreferences (string filename, string username, Int  Userpswd ){  7           Boolean Issavedatasuccess = False ; //  Mark of successful data storage  8 Sharedpreferences = Mcontext. getsharedpreferences (filename, context. mode_private );  9 Sharedpreferences. editor edit = sharedpreferences. Edit (); //  Create a sharedpreferences. Editor object  10 Edit. putstring ("username", username ); //  Store Data  11 Edit. putint ("userpswd" , Userpswd );  12 Issavedatasuccess = edit. Commit (); //  Submit Storage Data  13           Return Issavedatasuccess;  14 }

Through the aboveCode, We created a data storage file of context. mode_private (default operation mode), which can save two items: username and userpswd.

1.2 monomer Test

To verify the correctness of the above code, we can write a single test code to quickly verify it. The specific standalone test code is as follows:

 1       /*  2   * Function: standalone test. Save the data to the sharedpreferences object.  3   * Author: blog Park-still indifferent  4       */  5       Public   Void  Savedata (){  6 Context context = Getcontext ();  7 Mysharedpreferences = New  Mysharedpreferences (context );  8 String filename = "userinfo "; //  File Name  9 String username = "Jack "; //  Stored data  10           Int Userpswd = 123; //  Stored data  11           Boolean Flag = Mysharedpreferences. savedatatosharedpreferences (filename, username, userpswd );  12 Log. I (TAG, "-->" + Flag );  13 }

Run the standalone test. We can see that the flag output in the log is true, indicating that the data is successfully stored. In addition, we created a storage file named "userinfo" and saved two data contents: username = "Jack" and userpswd = 123.

So where is the "userinfo" file stored? The answer is/data/<package name>/shared_prefs directory, as shown in 2.

Figure 2 shared preferences file directory for data storage

Note that when data is stored in shared preferences, files are stored in XML format by default.

Open the "userinfo. xml" file and you can see content 3.

Figure 3 content of the "userinfo. xml" File

It can be seen that the above Code can indeed achieve correct data storage.

1.3 Use shared preferences to read data

Then, how can we read the content stored in the "userinfo. xml" file in the program? The following code provides an implementation solution.

 1       /*  2   * Function: reads data from the sharedpreferences object.  3   * Param: File Name of the data stored by filename  4   * Author: blog Park-still indifferent  5        */  6      Public Map <string, Object> Readdatafromsharedpreferences (string filename ){  7 Map <string, Object> map = New Hashmap <string, Object> (); //  Map object used to store read data  8 Sharedpreferences = Mcontext. getsharedpreferences (filename, context. mode_private );  9 String username = sharedpreferences. getstring ("username ",""); // Read data from the sharedpreferences object  10           Int Userpswd = sharedpreferences. getint ("userpswd", 0 );  11 Map. Put ("username", username ); //  Store the read data to the map object.  12 Map. Put ("userpswd" , Userpswd );  13           Return  Map;  14 }

The preceding Code reads data from the shared preferences object and saves the read data to the map object.

Related Article

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.