Sharedpreferences for Android Data Storage Operations

Source: Internet
Author: User

Android data storage methods include:

1. sharedpreferences

2. File Storage

3. SQLite Storage

4. Content Provider)

5. Network

 

1. sharedpreferences

Android is used to store simple configuration information. Is a data type of the key-value relationship. The data is stored in an XML file.

First, create a sharedpreferences object.

 SharedPreferences s=getSharedPreferences("filename", 0);

The first parameter is the saved file name. You can see the corresponding file in/data/package name/shared_prefs of fileexplorer.

Read files:
s.getString("name", "")

The first parameter is the key, and the second parameter is the default value;

Of course, there are also different methods for getting values.

Write File:
s.edit() .putString("name", edit_name.getText().toString()) .commit();

S. Edit () indicates entering the editing status

Putstring () Press Value

Commit () submitted content

Similarly, put supports pushing different values:

 

All code:

Public class main extends activity {edittext edit_name; button but_sub;/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); edit_name = (edittext) This. findviewbyid (R. id. edit_name); // get a sharedpreferences object sharedpreferences S = getsharedpreferences ("FILENAME", 0); edit_name.settext (S. getstring ("name", ""); but_sub = (button) This. findviewbyid (R. id. but_sub); but_sub.setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stub sharedpreferences S = getsharedpreferences ("FILENAME", 0 ); s. edit (). putstring ("name", edit_name.gettext (). tostring ()). commit ();}});}}

Preferences can only be used in the same package and cannot be used in different packages. the stored data is saved in plaintext in the mode of healthy values, which is suitable for storing simple data types.

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.