Sharedpreferences of Android Easy data storage

Source: Internet
Author: User

Andorid provides a variety of ways to store data, such as the "SQLite operation of the Android data store", as mentioned earlier, for more complex data storage. However, there are some simple data stores that can be cumbersome if they are used in a sqlite fashion. For example, it would be unnecessary and time-consuming to record whether a user has accessed data such as the Welcome page of the app, if using SQLite. So Andorid provides another way to store simple data sharedpreferences. Sharedpreferences is a lightweight data storage method that supports only Boolean, int, long, float, String, and set<string> data types.

  

In addition, sharedpreferences cannot add and modify data directly, and adding and modifying data needs to be done through the Sharedpreferences editor. The specific implementation can refer to the official documentation: Http://developer.android.com/reference/android/content/SharedPreferences.html. Let's see how sharedpreferences is adding, modifying, and reading data.

Create a new project with the name Dataoperate, and then add the following code to the Mainactivity.java

Sharedpreferences sharedpreferences = getsharedpreferences ("appsetting", mode_private); Sharedpreferences.editor Editor=Sharedpreferences.edit (); Editor.putboolean ("Isfirstview",false); Editor.putstring ("AppName", "Sharepreferences Demo"); Editor.commit ();//synchronous commit to disk file, so there will be blocking and so on, if you want to ensure the successful submission, try to use commitEditor.apply ();//It is more efficient to commit to memory and then asynchronously commit to disk, but there is no return message. Boolean Isfirstview= Sharedpreferences.getboolean ("Isfirstview",false); System.out.println ("Isfirstview:" +Isfirstview); String AppName= Sharedpreferences.getstring ("AppName", "" "); System.out.println ("AppName:" +appName); String author= Sharedpreferences.getstring ("Author", "author null"); System.out.println ("Author:" + Author);

To run the app into the emulator, you can see the following output:

09-12 10:34:50.627    false09-12 10:34:50.627    2669-2669/com.example.ibm.dataoperate i/  System.out:AppName:SharePreferences Demo09-12 10:34:50.651    null

This is the simple application of sharedpreferences. However, here are a few places to be aware of:

1. There are three ways to create or read a file:MODE_PRIVATE、MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE。

However, the official recommended way of use for mode_private is the default way. As for the reason, the official document says:

This constant is deprecated in API level. Creating World for this access mode would remain on a file, such as when it goes through a backup and Restore. File creation Mode:allow All and applications to has read access to the created file.

Both mode_world_readable and mode_world_writeable are very dangerous, and if both of these methods are used, they can lead to security vulnerabilities in the application. So the official recommended way to use the mode_private.

2. Editor submits data in two ways. One is committed by commit, and the other is submitted by apply.

This is what the official document says:

Commit your preferences changes back from ThisEditor to the Sharedpreferences object it is editing. This atomically performs the requested modifications, replacing whatever are currently in the Sharedpreferences.note that W Hen editors is modifying preferences at the same time and the last one to call apply wins. Unlike commit (), which writes its preferences out to persistent storage synchronously, apply () commits it changes to the Inch-memory Sharedpreferences immediately but starts a asynchronous commit to disk and you won ' t is notified of any failures. If another editor on this sharedpreferences does a regular commit () when a apply () is still outstanding, the commit () WI ll block until all Async commits is completed as well as the commit itself.as Sharedpreferences instances is singletons within a process, it' s safe to replace any instance of commit () with apply () if you were already ignoring the return value.You Don' t need to worry on Android component lifecycles and their interaction with apply () writing to disk. The framework makes sure in-flight disk writes from apply () complete before switching states.The sharedpreferences.editorInterfaceIsn ' t expected to be implemented directly.  However, if you previously did implement it and is now getting errors about missing apply (), can simply call commit () from apply ().

The difference between the two submissions is that (English is not good, please point out the error):

A, apply is to submit data to memory, and then asynchronously write to the file, the efficiency is high, and commit is committed to memory and write to the file, so the efficiency is relatively low, if the data is large, there will be a blocking situation.

b, because apply is a way of using asynchronous commits, there is no return value, and the message is not returned even if the write fails. The commit has a return value that ensures that the data is written to the disk file normally. Therefore, if you need to ensure the integrity of the data write, it is best to use commit.

3. Data storage method and location

After you successfully run the app, you can see "Appsetting.xml" (the name of the file named Custom) in Shared_prefs (full path for/data/data/Project package/shared_prefs/name) in the app installation directory. When you open the XML file, you can see that the standard XML file key-value pair is used to store it.

Storage location:

File contents:

4. Preferenceactivity Create configuration Preferences interface

In addition, Android also offers preferenceactivity Quick Create preferences page. Unlike Sharedpreferences, Sharedpreferences is a pure operation that creates a Setup page, while preferenceactivity allows you to quickly create a setup interface and store data. In this first not in-depth explanation, another day is free to write an article to describe. Interested can be viewed in the official documentation: Http://developer.android.com/reference/android/preference/PreferenceActivity.html. Wall Oh! Saying goes...

Sharedpreferences of Android Easy data storage

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.