SharedPreference for storing Android data

Source: Internet
Author: User

SharedPreference for storing Android data
Most of the problems processed in the program are related to data. The read data is displayed on the UI, And the read data can be local or network. You can save user data to a bucket, either a local database or a file, or a network server. In short, most programs are dealing with data. Data storage in Android is convenient and flexible. Today, we will talk about data storage on the official website. Most Android applications need to store data. In the Android life cycle method onPause, you can save the progress data of the user in the program and read and restore the data when the user enters the program again. Some applications do not need to save the user's progress information, but the user's settings must be saved. Many applications need to save a large amount of data to databases or files. For example, TV applications need to save a large amount of channel information. The following describes how data is stored in Android. Key-value set: If you have a relatively small number of key-value datasets that need to be saved, SharedPreferences should be able to meet your needs. A SharedPreferences object directs to a Shared Preference file that stores data in the form of a key-value pair. It provides some convenient methods for reading and writing data. Each SharedPreferences file is managed by the Android framework. It can be accessed only by applications that create it, or shared with other applications. How to Use SharedPreferences to save data? Get the SharedPreferences object: you can create a new Shared Preference Shared file. if it already exists, the SharedPreferences object pointing to the Shared file is directly returned. You can do this in either of the following ways: getSharedPreferences (String name, int mode) This Party calls the Context object to return a unique SharedPreferences object. The only object here refers to the unique SharedPreferences found by name, if no data is found, a name is used to create one. The only benefit is that you can read the value immediately after saving it in another place. The mode is used to differentiate the SharedPreferences object sharing type created. MODE_PRIVATE indicates that the application is private, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE indicate that the global read or write permissions are applied, and MODE_MULTI_PROCESS indicates that cross-process access is enabled. GetPreferences (int mode) This method is called by the Activity object and creates a SharedPreferences object that can only be accessed by the Activity. This method is the method encapsulated above, the default created SharedPreferences name is the Activity name, so you do not need to pass this parameter. mode is only available in MODE_PRIVATE, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE. MODE_MULTI_PROCESS is missing because only the Activity has access permission, therefore, cross-process is useless. For 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 where the Fragment is located (the Activity is inherited from the Context), R. string. preference_file_key is the name of the SharedPreferences, and mode is Context. the private type of MODE_PRIVATE. Note: When you name SharedPreferences, it is better to be complex. This ensures that there are no duplicate names but SharedPreferences belonging to different applications, it is best to add other components with your application package name, such as "com. example. myapp. PREFERENCE_FILE_KEY ". The code used to obtain the SharedPreferences of an Activity is as follows: SharedPreferences sharedPref = getActivity (). getPreferences (Context. MODE_PRIVATE); a private SharedPreferences object of the Activity is created above. Note: When you create SharedPreferences, the mode value is MODE_WORLD_PRIVATE or MODE_WORLD_WRITEABLE. The Shared Preferences file you create can be accessed by other applications. Both modes are dangerous because other applications can access them, which may cause data leakage. Google recommends that you do not use this mechanism for data sharing and transmission. You can use other methods to replace this mechanism, such as ContentProvider, BroadcastReceiver, or Service. Write Data to the Shared Preferences file: Write Data to Shared Preferences by obtaining SharedPreferences. editor object, call some putXX (key, value) Methods of the object to write the value corresponding to the key, and then call the commit () method to submit the written data. 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();  

 

SharedPreferences. the putXX (String key, data type) method of the Editor object can save data of the boolean, int, float, long, String, and Set <String> types, however, the put method only establishes the data contact of the key-Value Pair and does not save it until you call the commit () or apply () method. You can call remove (String key) to clear the data corresponding to the key (you also need to call the commit method to submit the operation). You can also call the clear () method to clear all the data. Note: Both commit () and apply () commit operations on data, but there are some differences: 1. The commit method has a return value, and the return value is a boolean variable, indicates whether your save action is successful, and apply does not return a value. Therefore, if you do not need to return a value or do not care whether the submission is successful, you can use apply instead of commit; 2. apply submits data changes to the memory and then asynchronously saves them to the disk. The commit operations are synchronous, therefore, it is more efficient to apply when frequently submitting data changes. read data from the Shared Preferences file: it is easier to read the stored data from the Shared Preferences file, you can use the getXX method of the SharedPreferences object. The Code is 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 getXX (String key, defValue) method key of SharedPreferences is previously called SharedPreferences. the key of the Editor's put (String key, data type) method. defValue is the default data returned when the corresponding key cannot be found. Summary: Save the data in four steps: 1. Get the SharedPreferences object; 2. Get the SharedPreferences. editor object; 3. Call the put Method to add data; 4. Call the commit method to save data; the method to obtain data is very simple. There are two steps: 1. Get the SharedPreferences object; 2. Call the get method to obtain the value corresponding to the key. The above is the knowledge of using SharedPreferences for data storage. It basically contains all the methods and precautions for using SharedPreferences, in some cases, please criticize and correct them.

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.