Sharedpreference of Android Data storage

Source: Internet
Author: User

Objective:

Most of the problems that are dealt with in the program are related to data, and reading data is displayed on the UI, and the data read can be local or network. Save user data to storage space, can be a local database, file, etc., or it can be saved to a Web server. In short, most of the programs are dealing with data. Android data storage is more convenient and flexible, today according to the official website to say that data preservation.

Most Android applications need to store data, and in the Android life cycle method OnPause, you can save the user's progress data in the program and read the recovery when the user enters the program again. Some applications may not need to save the user's progress information, but the user's setup information for the application must be saved. Many applications need to save a lot of data to the database or file, such as watching TV applications, need to save a lot of channel information. Here's a look at how data is stored in Android.

Key-value A collection of key values to save data:

If you have some relatively few key-value datasets that need to be saved, then sharedpreferences should be able to satisfy you. A Sharedpreferences object points to a shared preference file that stores data as a key-value pair, which provides some convenient ways to read and write data. Each sharedpreferences file is managed by the Android framework and can be accessed only by the application that created it, or it can be shared with other applications. How to save data with Sharedpreferences?

Get Sharedpreferences object:

You can create a new shared Preference share file, and if it already exists, return directly to the Sharedpreferences object that is pointing to the shared file, there are two ways to do this:

    • Getsharedpreferences (String name, int mode)
      This side pass is called by the context object, returning a unique Sharedpreferences object, where the only reference is the only corresponding sharedpreferences that is found by name, and the name is used to create one if it is not discovered. The only benefit is that you will be able to read this value in a different place immediately after you save it. Use MODE to differentiate between the created Sharedpreferences object share type, mode_private indicates that the application is private, mode_world_readable and mode_world_writeable are global read or write permissions, Mode_multi_process indicates that it can be accessed across processes.
    • getpreferences (int mode)
      This method is called by the activity object and creates a Sharedpreferences object that can be accessed only by that activity, which is the method that is encapsulated above, and the sharedpreferences name created by default is the name of the activity. So do not pass this parameter, MODE only Mode_private, mode_world_readable and mode_world_writeable three optional, lack of mode_multi_process, Cross-process is useless because only the activity has permission to access it.
As an example:
Context context = getactivity (); Sharedpreferences sharedpref = context.getsharedpreferences (        getString (R.string.preference_file_key), Context.mode_private);

  

The above code is called in a fragment, getactivity () is the activity object that gets the fragment (activity is inherited from the context), R.string.preference_file_ Key is the name of the Sharedpreferences, MODE is the context.mode_private private type. Note: When you give Sharedpreferences a name, it's best to be more complex, so that you can guarantee that there will be no duplicate names but belong to different applications sharedpreferences, preferably with your app package name plus other components, such as " Com.example.myapp.PREFERENCE_FILE_KEY ". Get the Sharedpreferences code for an activity as follows:
Sharedpreferences sharedpref = getactivity (). Getpreferences (Context.mode_private);
Above is the creation of an activity-private sharedpreferences object.
Note: When you create Sharedpreferences, the mode value is Mode_world_private or mode_world_writeable, and you create a shared The preferences file can be accessed by other applications. Both of these mode are dangerous because other applications can access it, so it can cause data to leak out. Google's advice is to try not to use this mechanism for data sharing, which can be replaced by other methods, such as using contentprovider,broadcastreceiver or service.
Write data to the shared preferences file:

Writes the data to a shared preferences by getting the Sharedpreferences.editor object, calling some Putxx (Key,value) method of the object to write the value corresponding to the key, and then invoking commit () Method commits the write completion, the code is as follows:

Sharedpreferences sharedpref = getactivity (). Getpreferences (Context.mode_private); Sharedpreferences.editor Editor = Sharedpref.edit (); Editor.putint (GetString (R.string.saved_high_score), Newhighscore); Editor.commit ();

  

The PUTXX (String key, data type) method of the Sharedpreferences.editor object can hold data of type Boolean, int, float, long, string, and set<string>. But the put method simply establishes the data connection for the key-value pair and does not save until you call the commit () or the Apply () method. Call Remove (String key) to clear the data for the key (you also need to call the Commit method commit), or you can call the clear () method to erase all the data.
Note: commit () and apply () are all committed to the data, but they are still somewhat different: 1, the Commit method has a return value, the return value is a Boolean variable, indicating whether your save action is successful, apply is not a return value, So if you do not need to return a value, do not care whether the submission is successful can be used to replace commit;2, apply is to commit the data changes to memory, and then asynchronously saved to disk, and commit these two operations are synchronous, Therefore, apply is more efficient when making frequent submissions of data changes;
Reading data from a shared preferences file: The data saved before reading from a shared preferences file is relatively simple and can be accomplished by sharedpreferences the Getxx method of the object, as follows:
Sharedpreferences sharedpref = getactivity (). Getpreferences (context.mode_private); int defaultvalue = GetResources (). Getinteger (R.string.saved_high_score_default); Long highscore = Sharedpref.getint (getString (r.string.saved_high_ Score), DefaultValue);

  

The Sharedpreferences getxx (string key, Defvalue) method key is the key that was previously called by the put (string key, data type) method of the Sharedpreferences.editor. Defvalue is the default data that is returned when no data for the corresponding key is found. Summary: Save the data in four steps: 1, Get Sharedpreferences object, 2, Get Sharedpreferences.editor object, 3, call put method to add data, 4, call commit to save data, get the data is simple, two steps: 1, Get Sharedpreferences object, 2, call get method to get key corresponding value;

The above is the use of sharedpreferences for data preservation knowledge, basically contains all the methods and precautions to use sharedpreferences, where is not good enough to ask the great God to criticize.

This article is original, reproduced please indicate the source, offenders must investigate

Focus on the public platform: the Programmer Interaction Alliance (coder_online), you can get the first original technical articles, and (Java/c/c++/android/windows/linux) technology Daniel Friends, online communication programming experience, get programming basics, Solve programming problems. Programmer Interactive Alliance, Developer's own home.

Sharedpreference of Android Data 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.