Android:sharedpreferences Storage

Source: Internet
Author: User

Unlike how files are stored, sharedpreferences stores data in a way that uses key-value pairs. That is, when you save a piece of data, you need to give the data a corresponding key, so that when the data can be read by this key to the corresponding value to be taken out. And Sharedpreferences also supports a variety of different data type storage, if the stored data type is integer, then the data read is an integral type, the stored data is a string, the data read is still a string.

This way you should be able to clearly feel that using sharedpreferences for data persistence is much more convenient than using files, so let's take a look at its specific usage.

6.3.1 storing data in sharedpreferences

To use Sharedpreferences to store data, you first need to get to the Sharedpreferences object. Android

There are three main methods for getting Sharedpreferences objects.

1. Getsharedpreferences () method in the Context class this method receives two parameters, the first parameter specifies the name of the Sharedpreferences file, and if it refers to a

A file that is not present will create one, and the sharedpreferences file is stored in the/data/data/<package name>/shared_prefs/directory. The second parameter specifies the mode of operation, and there are two main modes to choose from, 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 sharedpreferences file. Mode_multi_process is typically used to read and write to the same sharedpreferences file in multiple processes. Similarly, both the mode_world_readable and mode_world_writeable models have been deprecated in Android version 4.2.

2. The Getpreferences () method in the Activity class

This method is similar to the Getsharedpreferences () method in the Context, but it only receives an operation mode parameter, because using this method automatically takes the currently active class name as the sharedpreferences filename.

3. Getdefaultsharedpreferences () method in the Preferencemanager class this is a static method that receives a Context parameter and automatically uses the current application's package masterpiece

Name the sharedpreferences file for the prefix.

After getting the Sharedpreferences object, we can begin to store data in the Sharedpreferences file, which can be divided into three steps.

1. Call the edit () method of the Sharedpreferences object to get a Sharedpreferences.editor object.

2. Add data to the Sharedpreferences.editor object, such as adding a Boolean data to use

Putboolean method, adding a string uses the Putstring () method, and so on.

3. The commit () method is called to commit the data that was added, thus completing the data store operation. Unconsciously has introduced a lot of theoretical knowledge, then we quickly through an example to experience

Sharedpreferences the use of storage. Create a new Sharedpreferencestest project, and then modify the Activity_main.xml

The code in, as follows:

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent " android:orientation= "vertical" >

<buttonandroid:id= "@+id/save_data" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "Savedata"

/>

</LinearLayout>

Here we don't do any complicated functions, just simply place a button to store some data in

Sharedpreferences file. Then modify the code in the mainactivity as follows:

public class Mainactivity extends Activity {

Private Button SaveData;

@Override

Protected voidoncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);

SaveData = (Button) Findviewbyid (r.id.save_data);

Savedata.setonclicklistener (New Onclicklistener () {

@Override

public void OnClick (View v) {

Sharedpreferences.editor Editor = getsharedpreferences ("Data", Mode_private). Edit ();

Editor.putstring ("name", "Tom"); Editor.putint ("Age", Editor.putboolean); ("Married", false);

Editor.commit ();

}

});

}

}

As you can see, the button is first registered with a click event, and then in the Click event, the Getsharedpreferences () method is used to specify the Sharedpreferences file name as data, and To the Sharedpreferences.editor object. Then three different types of data are added to the object, and finally the commit () method is called to complete the data store operation.

Very simple, huh? Now you can run the program, go to the main interface of the program, click on the Save Data button. This time the data should have been saved successfully, but in order to confirm, we still need to use the File Explorer to view. Switch to the DDMS view and click on the File Explorer switch card and go to/data/data/com. Example.sharedpreferencestest/shared_prefs/directory, you can see that a The Data.xml file is shown in 6.6.

Figure 6.6

The next step is to click the Export button to export the file to your computer and view it in Notepad, as shown in Content 6.7.

Figure 6.7

As you can see, all the data we just added to the button's Click event has been successfully saved, and the Sharedpreferences file is managed using XML format for the data. Then we naturally have to look at how to read the data from the Sharedpreferences file.

Reading data from the Sharedpreferences

You should already be aware that using Sharedpreferences to store data is very simple, but there are better messages, which are actually easier to read from the Sharedpreferences file. The Sharedpreferences object provides a series of get methods for reading stored data, each of which corresponds to a put method in Sharedpreferences.editor, such as reading a Boolean data to use The Getboolean () method uses the GetString () method to read a string. 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.

Let's take a practical example and continue to develop on the basis of the Sharedpreferencestest project, modifying the code in Activity_main.xml as follows:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent " android:orientation= "vertical" >

<buttonandroid:id= "@+id/save_data" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "Save Data"

/>

<buttonandroid:id= "@+id/restore_data" android:layout_width= "match_parent" android:layout_height= "wrap_content "Android:text=" Restoredata "

/>

</LinearLayout>

A button to restore the data is added here, and we want to read the data from the Sharedpreferences file by clicking on this button. Modify the code in the mainactivity as follows:

public class Mainactivity extends Activity {

Private Button SaveData;

Private Button Restoredata;

@Override

Protected voidoncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);

SaveData = (Button) Findviewbyid (r.id.save_data);

Restoredata = (Button) Findviewbyid (r.id.restore_data);

......

Restoredata.setonclicklistener (New Onclicklistener () {

@Override

public void OnClick (View v) {

Sharedpreferences pref = getsharedpreferences ("Data",

Mode_private);

}

String name = pref.getstring ("name", "");

int age = Pref.getint ("Age", 0);

Boolean married =pref.getboolean ("married", false); LOG.D ("Mainactivity", "name is" + name); LOG.D ("Mainactivity", "Age was" + age); LOG.D ("Mainactivity", "Married is" +married);

});

}

}

As you can see, we first get the Sharedpreferences object through the Getsharedpreferences () method in the Click event of the Restore Data button, and then call its getString (), GetInt (), and Getboolean respectively. () method to get the name, age, and whether it was previously stored, if no corresponding value is found, the default value passed in the method is used instead, and the value is then printed out via Log.

Now rerun the program and click on the Restore Data button on the interface, and then look at the print information in LogCat, shown in 6.8.

Figure 6.8

All previously stored data has been successfully read out! Through this example, we have learned the knowledge of sharedpreferences storage. In contrast, sharedpreferences storage is much simpler and easier to store than text storage, with many applications, such as the preferences feature in many applications using sharedpreferences technology.

Android:sharedpreferences 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.