Usage of SharedPreferences in android development (including source code and running results), android source code
In Android Application Development, you often need to save simple types of data similar to configuration information, such as game player credits and whether to enable sound effects. The SharedPreferences class facilitates data storage and reading.
The SharedPreferences interface provides the following common methods to access the key-value pair in the SharedPreferences object:
Boolean contains (String key): determines whether the SharedPreferences object contains data with a key value.
Boolean getXxx (String key, xxx defaultValue): obtains the value of the specified key in the SharedPreferences object. If the key does not exist, the default value defaultValue is returned. Xxx can be boolean, float, int, String, long, and other basic types.
You can call the edit () method of SharedPreferences to obtain the Editor object. The Editor object is used to write data to the SharedPreferences object. The following common methods are available:
SharedPreferences prefs;
Editor editor = prefs. edit ();
Editor. clear (): clear Data
Editor. putXxx (String key, xxx value): stores data of the specified key to the SharedPreferences object. xxx can be of the basic types such as boolean, float, int, String, and long.
Editor. remove (String key): deletes data corresponding to the key.
Editor. apply (): Save the changes for Android 2.3 or later versions, asynchronous writing, and thread security.
Editor. commit (): Save the changes and write data synchronously. It blocks the calling thread, returns true if the write is successful, and false if the write fails.
SharedPreferences is an interface that can only be obtained through the getSharedPreferences (String name, int mode) method provided by Context. The mode parameter supports the following values:
Context. MODE_PRIVATE: it 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.
The data saved by SharedPreferences is still valid after the program is restarted, so it can be used to save some data set by the user.
Next, let's look at a demo. In one activity, click the "set" button to jump to another activity. After setting related options and restarting the application, we can see the result of the previous setting in the activity.
Xml code for main activity layout:
<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 = "vertical"> <Button android: id = "@ + id/setButton" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "Settings" android: textSize = "20dp"/> <LinearLayout android: 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> <LinearLayout android: layout_width = "match_parent" android: layout_height = "wrap_content" android: orientation = "horizontal"> <TextView android: id = "@ + id/languageLabel" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "recognition language:" android: textSize = "20dp"/> <TextView android: id = "@ + id/languageTextView" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: textSize = "20dp"/> </LinearLayout> </span>
Java code of 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 on 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="vertical" > <TextView android:id="@+id/engine_text_view" android:layout_width="match_parent" android: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:layout_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"/> <RadioButton 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" android:textSize="20dp"/> </RadioGroup> <TextView android:id="@+id/language_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/language_text_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_content" android:layout_height="wrap_content" android:text="@string/Chinese_radio_button" android:textSize="20dp"/> <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"/> <Button android:id="@+id/cancelButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cancel" android:textSize="20dp"/> </LinearLayout></LinearLayout></span>
Set the java code on 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 the radio button RadioButton listener of the recognition engine; RadioButton listener; // define the radio button RadioButton chineseRadioButton; RadioButton listener; RadioGroup engineGroup; radioGroup extends agegroup; Button okButton; Button cancelButton; public static final String PREF_OCR_ENGINE = "PREF_OCR_ENGINE"; public static final String comment = "comment"; SharedPreferences prefs; private String choosedEngine = ""; private String choosedLanguage = ""; @ Overridepublic void onCreate (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. export age_radio_group); okButton = (Button) findViewById (R. id. okButton); cancelButton = (Button) findViewById (R. id. cancelButton); prefs = getSharedPreferences ("set", MODE_PRIVATE); // Add the 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 () ;}}); required agegroup. 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 () ;}}); okButton. 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>
Below is:
After the first startup:
Setting page:
Click "save" and restart the application. The result of the previous setting is as follows:
Open the File Explorer of DDMS and save the SharedPreferences data in the/data/<package name>/shared_prefs folder, for example:
Export the xml file and open it, for example: