Sharedpreferences Usage in Android development (with screenshots of source code and running results)

Source: Internet
Author: User

In the development of Android applications, it is often necessary to keep some simple types of data similar to the configuration information, such as the player's points, whether the sound is turned on or not. The Sharedpreferences class provides the convenience for us to save and read this data.

The Sharedpreferences interface provides the following common methods for accessing Key-value pairs in Sharedpreferences objects:

Boolean contains (String key): Determines whether the Sharedpreferences object contains data with key values.

Boolean getXxx (String key, xxx defaultvalue): Gets the value corresponding to the specified key in the Sharedpreferences object. If the key does not exist, the default value of DefaultValue is returned. XXX can be a Boolean, float, int, String, long, and other basic types.

Call Sharedpreferences's edit () method to get the editor object, and write data to the Sharedpreferences object through the editor object, with the following common methods:

Sharedpreferences prefs;

Editor editor = Prefs.edit ();

Editor.clear (): Empty data

Editor.putxxx (String key, xxx value): The data corresponding to the specified key is stored in the Sharedpreferences object, and XXX can be a Boolean, float, int, String, long, and other basic types.

Editor.remove (String key): delete data corresponding to key

Editor.apply (): Save changes for Android 2.3 or later, asynchronous write, thread safe.

Editor.commit (): Save changes, synchronously write, it blocks the calling thread, the write succeeds returns True, and the write failure returns false.

Sharedpreferences is an interface that obtains an instance only through the Getsharedpreferences (String name, int mode) method provided by the context. The mode parameter supports several values:

Context.mode_private: can only be read and written by this application.

Context.mode_world_readable: Can be read only by other applications.

Context.mode_world_writeable: Can be read and written by other applications.

Sharedpreferences saved data is still valid after the program restarts, so it can be used to save some data set by the user.

Here is a demo of me, in one activity in the midpoint of the "Settings" button to jump to another activity, set the relevant options, restart the application, you can see the results of the last set in the activity.

Main activity Layout XML code:

<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:layout_width=" match_parent "android:layout_height=" match_parent "android:orientation=" vertic Al "> <button android:id=" @+id/setbutton "android:layout_width=" Match_parent "android:l ayout_height= "Wrap_content" android:text= "Settings" android:textsize= "20DP"/> <linearlayout A                  Ndroid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:orientation= "Horizontal" >            <textview android:id= "@+id/enginelabel" android:layout_width= "Wrap_content"                android:layout_height= "wrap_content" android:text= "recognition Engine:" android:textsize= "20DP"/>           <textview android:id= "@+id/enginetextview" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:textsize= "20DP"/> </LinearLayout> <linearlay Out android:layout_width= "match_parent" android:layout_height= "wrap_content" android:orientation= "hor Izontal "> <textview android:id=" @+id/languagelabel "android:layout_width=" wrap _content "android:layout_height=" wrap_content "android:text=" Recognition Language: "Android:textsize=" 20d P "/> <textview android:id=" @+id/languagetextview "android:layout_width=" Wrap_conte NT "android:layout_height=" Wrap_content "android:textsize=" 20DP "/> </LinearLayout> &l T;/linearlayout></span>

Java code for the main activity:

<span style= "FONT-SIZE:18PX;" >package my.set;import my.set.r;import Android.app.activity;import android.content.intent;import Android.content.sharedpreferences;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;public Class Testactivity extends Activity{textview Engineview; TextView Languageview; Button Setbutton; Sharedpreferences Sharedpreferences;class Buttonlistener implements Onclicklistener {public void OnClick (view view) { Intent Intent = new Intent (testactivity.this, Setactivity.class); startactivity (Intent);}} @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main); Engineview = (TextView) Findviewbyid (r.id.enginetextview); Languageview = (TextView) Findviewbyid ( R.id.languagetextview) Setbutton = (Button) Findviewbyid (R.id.setbutton); sharedpreferences = Getsharedpreferences (" Set ", mode_private); String enginestring = sHaredpreferences.getstring (Setactivity.pref_ocr_engine, ""); String languagestring = sharedpreferences.getstring (Setactivity.pref_recognized_language, ""); Setbutton.setonclicklistener (New Buttonlistener ()); Engineview.settext (enginestring); Languageview.settext (        languagestring); }}</span>

set the XML layout code for the interface:

<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:layout_width=" match_parent "android:layout_height=" match_parent "android:orientation=" vertic Al "> <textview android:id=" @+id/engine_text_view "android:layout_width=" Match_parent "Android        oid:layout_height= "Wrap_content" android:text= "@string/engine_text_view" android:textsize= "20DP"/> <radiogroup android:id= "@+id/engine_radio_group" android:layout_width= "Fill_parent" Android:layo ut_height= "wrap_content" android:orientation= "vertical" > <radiobutton android:id= " @+id/tesseract_radio_button "android:layout_width=" wrap_content "android:layout_height=" wrap_content "Android:text=" @string/tesseract_radio_button "android:textsize=" 20DP "/> <radi OBuTton android:id= "@+id/tesseract_and_cube_radio_button" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "@string/tesseract_and_cube_radio_button" Andro        Id:textsize= "20DP"/> </RadioGroup> <textview android:id= "@+id/language_text_view" Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "@string/language_t        Ext_view "android:textsize=" 20DP "/> <radiogroup android:id=" @+id/language_radio_group "                Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:orientation= "vertical" > <radiobutton android:id= "@+id/chinese_radio_button" android:layout_width= "Wrap_co Ntent "android:layout_height=" wrap_content "android:text=" @string/chinese_radio_button "a Ndroid:textsize= "20DP"/&Gt            <radiobutton android:id= "@+id/engilsh_radio_button" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "@string/english_radio_button" android:textsize = "20DP"/> </RadioGroup> <linearlayout android:orientation= "Horizontal" android:layout                _width= "Match_parent" android:layout_height= "wrap_content" android:gravity= "Center_horizontal" > <button android:id= "@+id/okbutton" android:layout_width= "Wrap_content" Android: layout_height= "Wrap_content" android:text= "@string/ok" android:textsize= "20DP"/> & Lt Button android:id= "@+id/cancelbutton" android:layout_width= "Wrap_content" android:layout _height= "Wrap_content" android:text= "@string/cancel" android:textsize= "20DP"/> </linearlayo Ut></LinearLayout></span> 

To set the Java code for the interface:

<span style= "FONT-SIZE:18PX;" >package My.set;import Android.app.activity;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;import Android.os.bundle;import Android.view.view;import Android.widget.button;import Android.widget.radiobutton;import Android.widget.radiogroup;import My.set.R;public Class Setactivity extends Activity {//define a radio button for the recognition engine RadioButton Tesseractradiobutton; RadioButton tessandcuberadiobutton;//defines the radio button RadioButton Chineseradiobutton of the recognition language; RadioButton Englishradiobutton; Radiogroup Enginegroup; Radiogroup LanguageGroup; Button OKButton; Button Cancelbutton;public static final string pref_ocr_engine = "Pref_ocr_engine";p ublic static final string Pref_recogn Ized_language = "Pref_recognized_language"; Sharedpreferences prefs;private String choosedengine = "";p rivate string choosedlanguage = ""; @Overridepublic void Oncrea Te (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.set); Tesseractradiobutton = (RadIobutton) Findviewbyid (R.id.tesseract_radio_button); Tessandcuberadiobutton = (RadioButton) Findviewbyid ( R.id.tesseract_and_cube_radio_button); Chineseradiobutton = (RadioButton) Findviewbyid (R.id.chinese_radio_button); Englishradiobutton = (RadioButton) Findviewbyid (R.id.engilsh_radio_button); enginegroup = (Radiogroup) findViewById ( R.id.engine_radio_group); LanguageGroup = (Radiogroup) Findviewbyid (r.id.language_radio_group); OkButton = (Button) Findviewbyid (R.id.okbutton); CancelButton = (Button) Findviewbyid (R.id.cancelbutton);p refs = Getsharedpreferences (" Set ", mode_private);//Add Event Listener Enginegroup.setoncheckedchangelistener (new Radiogroup.oncheckedchangelistener () {@ overridepublic void OnCheckedChanged (radiogroup group, int checkedid) {//TODO auto-generated method stubif (Checkedid = = R.id.tesseract_radio_button) {choosedengine = Tesseractradiobutton.gettext (). toString ();} else {choosedengine = Tessandcuberadiobutton.gettext (). toString ();}}); Languagegroup.setoncheckedchangelistener (New RadiogrouP.oncheckedchangelistener () {@Overridepublic void oncheckedchanged (radiogroup group, int checkedid) {//TODO Auto-generated method stubif (Checkedid = = R.id.chinese_radio_button) {choosedlanguage = Chineseradiobutton.gettext (). ToString ();} else {choosedlanguage = Englishradiobutton.gettext (). toString ();}}); O Kbutton.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated Method Stubsavepreferences (); Finish ();}}); Cancelbutton.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method Stubfinish ();}});} private void Savepreferences () {Editor editor = Prefs.edit (); editor.putstring (Pref_ocr_engine, choosedengine); Editor.putstring (Pref_recognized_language, choosedlanguage); Editor.commit ();}} </span>
here are the following:

The first post-boot interface:



Setup interface:


After clicking the Save button and restarting the application, you will see the last set result such as:


Open DDMS file explorer,sharedpreferences data is saved under the/data/data/<package Name>/shared_prefs folder, such as:


Export this XML file and open it as:


Sharedpreferences Usage in Android development (with source code and running results)

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.