Android------sharedpreferences

Source: Internet
Author: User

The data that Sharedpreferences saves is primarily data that resembles the configuration information format, so the data he saves is primarily a simple k-v pair.

The Sharedpreferences interface is primarily responsible for reading the application's preferences data, which provides the following common methods:




The Sharedpreferences interface itself does not provide the ability to write data, but instead, by invoking the edit () method through the internal interface of the Sharedpreferences, the editor object corresponding to it is obtained. Provides the following methods to write data.




Commit: When editor is finished, call the method to commit the modification.



From a usage perspective, sharedpreferences and editor combine very much like a map, where sharedpreferences is used to read data, and editor is used to write data.

Create a sharedpreferences:

It is an interface in itself and cannot be created directly, only through the getsharedpreferences (String name, int mode) provided by Contex to get the sharedpreferences instance. The second parameter supports a few values:

Contex.mode_private: Specifies that the sharedpreferences data can only be read and written by the application.

Contex.mode_world_readable: Specifies that the sharedpreferences data can be read by other applications, but cannot be written.

Contex.mode_world_writeable: Specifies that the sharedpreferences data can be read and written by other applications.



Small example: Write and read random numbers


There are only two buttons in the program, one for writing data, one for reading data, and therefore no layout code.


Import Java.text.simpledateformat;import Java.util.date;import Android.app.activity;import Android.content.sharedpreferences;import Android.os.bundle;import Android.preference.preference;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import android.widget.toast;/** * * @author Caesar * */public class Mainactivity extends Ac tivity {sharedpreferences preferences; Sharedpreferences.editor Editor; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main);p references = getsharedpreferences ("Crazyit", MODE_ world_readable); editor = Preferences.edit (); Button Read, Write;write = (button) Findviewbyid (r.id.write); read = (Button) Findviewbyid (R.id.read); Read.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stub/ /Read string-Data-preferences.getstring ("Time", null);//Read data int randomnum = Preferences.getint (" random ", 0); String result = time = = null? "You have not yet written the data": "Write Time:" + time+ "\ n the last generated random number is:" + randomnum; Toast.maketext (mainactivity.this, result, 0). Show ();}}); Write.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubsimpledateformat SDF = new SimpleDateFormat ("yyyy mm DD Day" + "HH:MM:SS");//Deposit Current time editor.putstring Sdf.format (New Date ()));//Deposit a random number editor.putint ("Random", (int) (Math.random () * 100));//submit all deposited data editor.commit ();});}}




Number of log programs used:


Import Android.app.activity;import Android.content.sharedpreferences;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import android.widget.toast;/** * Record the number of applications used: *  * @author Caesar *  */public class Mainactivity extends Activity {sharedpreferences preferences; Sharedpreferences.editor Editor; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main);p references = getsharedpreferences ("Count", Mode_world _readable); editor = Preferences.edit (); int count = Preferences.getint ("Count", 0); Toast.maketext (Mainactivity.this, "The program has been used:" + count + "Times", 0). Show (); Editor.putint ("Count", ++count); Editor.commit ();}}




Read and write sharedpreferences for other applications:

Prerequisite: Specify Permissions

Steps:

1. Need to create contex for other programs

2. Call the Contex getsharedpreferences (String name, int mode) of the other application to get the Sharedpreferences object of the response

3. If you need to write data to sharedpreferences data from another application, call the Edit method of the sharedpreferences to get the editor of the response



Import Android.app.activity;import Android.content.context;import Android.content.sharedpreferences;import Android.content.pm.packagemanager.namenotfoundexception;import Android.os.bundle;import Android.view.Menu;import Android.view.menuitem;import android.widget.textview;/** * * @author Caesar * */public class Mainactivity extends Activi ty {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Context Usecount = null;try {//Get other application locks corresponding to Contexusecount = Createpackagecontext ("Com.example.sharedpreferencesdemo2 ", context.context_ignore_security);} catch (Namenotfoundexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Use the Contex of other programs to get the corresponding sharedpreferencessharedpreferences preferences = Usecount.getsharedpreferences ("Count", context.mode_world_readable); int count = Preferences.getint ("Count", 0); TextView show = (TextView) Findviewbyid (r.id.show); Show.settext ("SharedPreferencesDemo2 already in use" + Count + "Times");}} 



Android------sharedpreferences

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.