Android Learning 10 (Android Sharepreferences storage)

Source: Internet
Author: User

Unlike the way files are stored, Sharepreferences uses key-value pairs to store data, that is, when you save data, you need to provide a corresponding key to the data so that when you read the data, you can take the corresponding value out of the key. and Sharepreferences supports a variety of different data type storage, if the stored Data Book shaping type, read out the data is also shaped, the stored data is a string, the data read is still a string.

To use Sharepreferences to store data, first to get to the Sharepreferences object, the Android system mainly provides 3 ways to get sharepreferences objects.

Getsharepreferences () method in the 1.Context class: The method receives 2 parameters, one parameter specifies the name of the Sharepreferences file, and if the specified file does not exist, it creates one. sharepreferences files are stored in the/data/data/<packagename>/shared_prefs/directory. The second parameter specifies the mode of operation, with the main 2 modes selectable, mode_private and mode_multi_process. Mode_private is still the default mode of operation, and the direct incoming 0 effect is the same, indicating that only the current application can read and write to this sharepreferences file. mode_multi_process is typically used to read and write to the same sharepreferences file in multiple processes .

Getpreferences () method in 2.Activity class: This method is similar to the Get Sharepreferences () method in the context, but only receives an operation mode parameter, Because this method is used, the currently active class name is automatically sharepreferences.

Getdefaultsharedpreferences () method in the 3.PreferenceManager class: This is a static method that receives a context parameter and automatically uses the current application's package name as a prefix to name Sharepreferences file.

Once you get the Sharepreferences object, you can begin to store data in the Sharepreferences file, which is divided into three implementations:

< Span style= "font-size:18px" > 1. Calling sharepreferences object to get a

< Span style= "font-size:18px" > < Span style= "font-size:18px" >2. style= "font-size:18px" to

3. The commit () method is called to commit the data that was added, thus completing the data store operation.

Save data to Sharepreferences

Let's take a little example to test the above, create a new Sharepreferencestest project, and then modify the code in the Activity_main.xml as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical" >    <button        android:id= "@+id/save_data"        android:layout_ Width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "save Data"/></ Linearlayout>


The above code is relatively simple, not much to say, the following changes the code inside the Mainactivity class, as follows:

Package Com.jack.sharedpreferencestest;import Android.app.activity;import android.content.SharedPreferences; Import Android.os.bundle;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity {private Button saveData; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Savedata= (Button) Findviewbyid (r.id.save_data); Savedata.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stub//gets Sharedpreferences.editor object Sharedpreferences.editor editor=getsharedpreferences ("Share", MODE_PRIVATE). Edit (); editor.putstring ("Name", "Jack"); Editor.putint ("Age", "n"); Editor.putboolean ("Married", false); Editor.commit ();//Submit data}}); @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflatER (). Inflate (R.menu.main, menu); return true;}} 

Run the program, click on the Save Data button, this time the information has been saved, we use the file Exploer to view, into the/data/data/com.jack.sharedpreferencestest/shared_prefs/ directory, you can see one of the following share files





Export the file to see the contents as follows:



Note: Sometimes when we run the program to view the file Explorer, we find that there are no files in it, which may be due to the fact that we did not select the correct running process in devices, just click on the package name of the currently running program in the following place, where the black coils are:



The File Explorer will then display the directory structure.


< Span style= "font-size:18px" > from Read data in sharepreferences

simple to read data from Sharepreferences, thesharepreferences object provides a series of get methods for reading stored data, each of which corresponds to A put method in Sharepreferences.editor. These get methods receive two parameters, the first parameter is the key, the key used to pass in the stored data can get the corresponding value, the second parameter is the default value, that is, when the incoming key cannot find the corresponding value, the default value will be returned.

To modify the above project, first modify the code in the ACTIVITY_MAIN.XLM as follows:

< Span style= "font-size:18px" > /span>

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical" >    <button        android:id= "@+id/save_data"        android:layout_ Width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "save Data"/>    <button        android:id= "@+id/restore_data"        android:layout_width= "match_parent"        android:layout_height= "wrap _content "        android:text=" restore Data "/>            </LinearLayout>

To modify the code in Mainactivity:

< Span style= "font-size:18px" > /span>

Package Com.jack.sharedpreferencestest;import Android.app.activity;import android.content.SharedPreferences; Import Android.os.bundle;import android.util.log;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity {private button Savedata;private button restoredata; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Savedata= (Button) findViewById ( R.id.save_data) restoredata= (Button) Findviewbyid (r.id.restore_data); Savedata.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stub// Get Sharedpreferences.editor object Sharedpreferences.editor editor=getsharedpreferences ("Share", MODE_PRIVATE). Edit (); Editor.putstring ("name", "Jack"), Editor.putint ("Age", "n"), Editor.putboolean ("Married", false); Editor.commit ();// Submit data}}); Restoredata.setonclicklistener (New OnCLicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubsharedpreferences pref= Getsharedpreferences ("Share", mode_private); String name=pref.getstring ("name", null), int age=pref.getint ("age", 0), Boolean married=pref.getboolean ("Married", FALSE); LOG.D ("Mainactivity", "name is" +name); LOG.D ("Mainactivity", "Age is" +age); LOG.D ("Mainactivity", "Married is" +married);}); @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}

To run the program, click the Restore Data button to view the log as follows:


The above small example is to read the contents of the Sharepreferences file, you can extrapolate oh.


The use of the Sharepreferences file is summarized here, the following article I will summarize the use of the Android data SQLite.


Reprint Please specify: http://blog.csdn.net/j903829182/article/details/40952301

Android Learning 10 (Android Sharepreferences storage)

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.