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. Editor editor;

 

@ Override

Public void onCreate (Bundle savedInstanceState)

{

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

// Obtain the SharedPreferences object that can only be read and written by this application.

Preferences = getSharedPreferences ("crazyit", MODE_WORLD_READABLE );

Editor = preferences. edit ();

Button read = (Button) findViewById (R. id. read );

Button write = (Button) findViewById (R. id. write );

Read. setOnClickListener (new OnClickListener ()

{

@ Override

Public 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 written data yet"

: "Write time:" + time

+ "\ N the random number generated last time is:" + randNum;

// Use the Toast prompt

Toast. makeText (SharedPreferencesTest. this,

Result, 5000)

. Show ();

}

});

Write. setOnClickListener (new OnClickListener ()

{

@ Override

Public void onClick (View arg0)

{

SimpleDateFormat sdf = new SimpleDateFormat ("MM dd, yyyy"

+ "Hh: mm: ss ");

// Current storage 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:

 

Author: rhljiayou

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.