Getting started with Android: sharedpreferences

Source: Internet
Author: User
Document directory
  • 1. Save
  • 2. Read
I. sharedpreferences application scenarios

Sharedpreferences is used to save parameters;

It is saved as an XML file in the/data/package/shared_prefs directory;

Ii. sharedpreferences core code

1. Save

Sharedpreferences preference = context. getsharedpreferences ("xiazdong", context. mode _); // obtain sharedpreferenceseditor editor = preference. edit (); // get the editor. putstring ("name", "value"); // enter the string-type parameter editor. putint ("name", value); // Insert the integer parameter editor. commit (); // submit

2. Read

Sharedpreferences preference = context. getsharedpreferences ("FILENAME", context. mode_private); string name = preference. getstring ("name", "defaultvalue"); // obtain the string type parameter named name. Otherwise, the value is defavaluvalueint age = preference. getint ("name", defaultvalue );

Because this method is very simple, you do not need to explain it here;

Iii. Internal principles we mentioned earlier that sharedpreferences are stored in the/data/shared_prefs directory in XML format. Here we will verify this. If we execute the following statement:

SharedPreferences preference = context.getSharedPreferences("xiazdong", Context.MODE_PRIVATE);Editor editor = preference.edit();editor.putString("name", "xiazdong");editor.putInt("age", 20);editor.commit();

The XML file is as follows:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map><string name="name">xiazdong</string><int name="age" value="20" /></map>

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.