[Android] Sharedpreference Getting Started

Source: Internet
Author: User

In order to save data with special characters to the file, Google provides the sharedpreference(shared parameters).

Sharedpreference is obtained through the getsharedpreference (name,mode) method of the Context Object objects, name parameter is the file name, Mode The parameters are those in the previous section.

Call the edit () method of the SP object to get the editor object

Call the putstring (key,value) method of the Editor object to put the data, much like the Map Collection

Invoke the commit () method of the Editor object to commit, much like a database transaction operation, to ensure that the data is committed successfully at the same time

Automatically create file /data/data/ package name /shared_prefs/ file name . XML

Read sp very simple, same get SP object, call SP object getString (key,defaultvalue) , the configuration information for the application can be saved using this. When a different type of value is saved, the node is its own type. Special character Inode is escaped.

Copy the project, after modifying the package name must re-guide the R file, the appeal method will not throw an exception, the function is defined as void no return type.

Java code:

    /*** Business method to save user name and method *@paramContext Contexts *@paramUsername User name *@paramPassword method *@return     */     Public Static voidsaveuserinfo (Context context,string username,string password) {sharedpreferences SP=context.getsharedpreferences ("config", context.mode_private); Editor Ed=Sp.edit (); Ed.putstring ("Username", username); Ed.putstring ("Password", password);    Ed.commit (); }

        // Read        Sharedpreferences sp=getsharedpreferences ("config", context.mode_private);        Et_username.settext (sp.getstring ("username", ""));        Et_password.settext (sp.getstring ("password", ""));

[Android] Sharedpreference Getting Started

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.