SharedPreferences usage,

Source: Internet
Author: User

SharedPreferences usage,

SharedPreferences is one of the four data storage technologies of Android. It is a lightweight data storage method. Its essence is to store key-value pairs of data based on XML files, usually used to store some simple configuration information

The object itself can only obtain data, but does not support storage and modification. The storage and modification must be implemented through the Edit object, such as the storage of the account when a user logs on. Because there is not much information to store, if the database is used for storage

Database Connection and other operations greatly affect efficiency. Therefore, SharedPreferences is used in Android to implement this function. It is generally used to store some simple data, such as String and int. When you encounter complex types of data

Type data is converted to Base64 encoding, and then the converted data is saved as a string in the XML file, and then saved in SharedPreferences. The method is as follows:

1. Store Data

(1) Use the getSharedPreferences method to obtain the SharedPreferences object

@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return mBase.getSharedPreferences(name, mode);
}

Eg: SharedPreferences settings = getSharedPreferences ("setting", 0 );

 

(2) Get the editor and make setting editable.

SharedPreferences. mEditor editor = settings. edit ();

 

(3) Data Storage

MEditor. putString (Config. USER_CODE, userCode );

MEditor. putString (Config. USER_PASS, userPass );

(4) Submit the save operation
Editor. commit ();

2. Read data

(1) Use the getSharedPreferences method to obtain the SharedPreferences object

(2) retrieve data

String name = settings. getString ("name", "Default Value ");

String url = setting. getString ("URL", "default ");

Int age = setting. getInt ("age", 1 );

 

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.