Sharedpreference is a lightweight data storage method provided by Android, which is mainly used to store simple configuration information, which is stored as a key-value pair, making it easy for us to read and deposit
Sharedpreference file is saved under /data/data/<package name>/shared_prefs Path
The Sharedpreferences object can be obtained by the Getsharedpreferences method of the activity itself.
Public abstract Sharedpreferences getsharedpreferences (String name, int mode);
Name: Represents the names of the XML files after saving
Mode: Represents the Operation permission pattern (private, readable, writable) of an XML document, using 0 or mode_private as the default mode of Operation permission.
1. Data read:
The key value of the corresponding key can be obtained by sharedpreferences the key of the object. There are different functions for different types of key values: Getboolean,getint,getfloat,getlong.
Public abstract string GetString (string key, String defvalue);
2. Data deposit:
The data is deposited through editor objects of the Sharedpreferences object . Use the editor function to set the key value, and then call commit () to commit the settings, write the XML file
Public Abstract Sharedpreferences.editor edit ();
Public abstract Sharedpreferences.editor putstring (string key, String value);
Public abstract Boolean commit ();
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android " android:orientation=" vertical " android:layout_width=" fill_parent " android:layout_ height= "Fill_parent" > <textview android:id= "@+id/textview" android:layout_width= "Fill_parent " android:layout_height=" wrap_content " android:text=" @string/hello "/> </LinearLayout>
Package com.android.test; Import android.app.Activity; Import android.content.SharedPreferences; Import Android.os.Bundle; Import Android.preference.PreferenceManager; Import Android.widget.TextView; public class Testsharedpreferences extends activity {/** Called when the activity is first created. */@Overrid e public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Sharedpreferences msharedpreferences = getsharedpreferences ("Testsharedpreferences", 0); Sharedpreferences msharedpreferences = preferencemanager.getdefaultsharedpreferences (this); int counter = Msharedpreferences.getint ("counter", 0); TextView Mtextview = (TextView) Findviewbyid (R.id.textview); Mtextview.settext ("This app has been started" + Counter + "times."); Sharedpreferences.editor meditor = Msharedpreferences.edit (); Meditor.putint ("Counter", ++counter); Meditor.commit (); } }
The data must be deposited via the editor of the Sharedpreferences object, which is similar to writing to the database after depositing (put) commit!
Preferencemanager[android]