Sharedpreferences for Android Data Storage

Source: Internet
Author: User

In Android, the available storage methods include sharedpreferences, file storage, SQLite database, content provider, and network.

To learn sharedpreferences:

Sometimes, applications need to save a small amount of data, and the data format is very simple: Common strings, scalar values, etc, for example, the various configuration information of the application, game player credits, etc., for this data, provides sharedpreferences for storage; you can imagine it is a small cookie, it uses key-value pairs to set simple data types (Boolean, Int, float, long, and string) stored in the XML file defined by data/package name/shared_prefs/in the private directory of the application.

1. Description

It provides a lightweight data storage method, through the eidt () method to modify the content, through the Commit () method to submit the modified content.

2. Important Methods

Public Abstract Boolean contains (stringkey): Check whether the file exists, where key is the XML file name.

Edit (): Create an editor for preferences. The created editor can modify the data in preferences, but the Commit () method must be executed.

Getall (): returns more data in preferences.

Getboolean (string key, Boolean defvalue): obtains boolean data.

Getfloat (string key, float defvalue): Get float data

Getint (string key, int defvalue): Get int data

Getlong (string key, long defvalue): Get long data

Getstring (string key, string defvalue): obtains string-type data.

Registeronsharedpreferencechangelistener (sharedpreferences. onsharedpreferencechangelistenerlistener): registers a callback function called when the preference changes.

Unregisteronsharedpreferencechangelistener (sharedpreferences. onsharedpreferencechangelistenerlistener): deletes the current callback function.

3. Important interfaces: sharedpreferences. Editor

Used to modify the content of the sharedpreferences object. All changes are made in batches in the editor, instead of being copied back to the original sharedpreferences or persistent storage, until you call commit () to store them persistently. Important methods:

Clear (): Clear the content.

Commit (): Submit changes

Remove (string key): delete preference

The following uses a simple example to demonstrate how to write and read data to and from sharedpreferences;

The layout file is simple:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center_horizontal"><Button android:id="@+id/write"android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/write"/><Button android:id="@+id/read"android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/read"/></LinearLayout>

The program code is as follows:

 

Package Org. crazyit. io; import Java. text. simpledateformat; import Java. util. date; import android. app. activity; import android. content. sharedpreferences; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. toast; public class sharedpreferencestest extends activity {sharedpreferences preferences; sharedpreferences. edito R editor; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // get the sharedpreferences object preferences = getsharedpreferences ("crazyit", mode_world_readable) that can only be read and written by this application; Editor = preferences. edit (); button READ = (button) findviewbyid (R. id. read); button write = (button) findviewbyid (R. id. write); read. setonclicklistener (New onclicklistene R () {@ overridepublic void onclick (view arg0) {// read string data string time = preferences. getstring ("time", null); // read int-type data int randnum = preferences. getint ("random", 0); string result = time = NULL? "You have not yet written data": "write time:" + time + "\ n the random number generated last time is:" + randnum; // use toast to indicate toast. maketext (sharedpreferencestest. this, results, 5000 ). show () ;}}); write. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view arg0) {simpledateformat SDF = new simpledateformat ("YYYY mm dd" + "HH: mm: SS "); // save it to the current time editor. putstring ("time", SDF. format (new date (); // store a random number editor. putint ("random", (INT) (math. random () * 100); // submit all stored data editor. commit ();}});}}

This program is a simple way to write data to read data;

Simple interfaces include:

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.