Android-SharedPreferences detailed usage

Directory

  • SharedPreferences
    • 1. Introduction
    • 2. Understand
      • 1 data storage
      • 2 Data reading
      • 3 common methods
        • 3.1 getSharedPreferences()
        • 3.2 edit()
        • 3.4 remove() remove data
        • 3.5 clear() clears data
        • 3.6 commit() submits and saves data
    • 3. Basic use
      • 1 an example
    • 4. Monitoring
    • 5. Performance analysis
    • 6. Points of attention during use
      • 1 Get the SharedPreferences object
      • 2 Data storage cycle
      • 3 SharedPreferences are not strongly typed
      • 4 Runtime exceptions caused by inconsistent value types
      • 5 Functions that need to execute commit

SharedPreferences

Question: 1

Is there any existing security mechanism for SharedPreferences?

If so, how to do it, common practice? or internal support?

Question: 2

What are the optimization suggestions and optimization space for SharedPreferences in reading and writing operations?

1. Introduction

A lightweight storage class particularly suitable for saving software configuration parameters.

(xml files are used to store data, and the files are stored in the /data/data//shared_prefs directory)

Sometimes it is necessary to save a small amount of simple type data locally, such as the user’s configuration data and some of the user’s non-strong security data (such as user name, user’s avatar, etc.)

Sometimes, you can also use SharedPreferences to store the user’s username and password, so as to achieve the needs/effects of simultaneous login when the user opens the APP and one-click login by remembering the password.

The data that needs to be stored is generally relatively simple.

The data types that SharedPreferences can save are: int, boolean, float, long, String, StringSet.

Tips: For Java or kotlin object type data (such as the User class used to store user information such as usernames and passwords), you can serialize it into a string for storage.

2. Understand

1 Data Storage

Saving data is generally divided into four steps:

  1. Use the getSharedPreferences method of the Activity class to obtain the SharedPreferences object;
  2. Use edit of the SharedPreferences interface to obtain the SharedPreferences.Editor object;
  3. Write key-value pairs through the putXXX method of the SharedPreferences.Editor interface;
  4. Save the key-value pair through the commit method of the SharedPreferences.Editor interface.

2 Data reading

Reading data is generally divided into two steps:

  1. Use the getSharedPreferences method of the Activity class to obtain the SharedPreferences object;
  2. Obtain data through the getXXX method of the SharedPreferences object;

3 Common methods

3.1 getSharedPreferences()
public abstract SharedPreferences getSharedPreferences (String name, int mode)

Function: Used to obtain SharedPreferences objects
(Look for SharedPreferences based on name, get it if it already exists, create a new one if it does not exist)

Parameters
name: naming
mode: mode, including
MODE_PRIVATE (can only be accessed by own application)
MODE_WORLD_READABLE (In addition to being accessed by yourself, it can also be read by other applications)
MODE_WORLD_WRITEABLE (In addition to being accessed by yourself, it can also be read and written by other applications)

It is worth noting that if the Activity only needs to create a SharedPreferences object, you can use the getPreferences method. You do not need to name the SharedPreferences object. You only need to pass in the parameter mode.

public SharedPreferences getPreferences (int mode)
3.2 edit()
abstract SharedPreferences.Editor edit()

Function: Used to obtain the Editor object of SharedPreferences

3.3 putXxx()

//Write boolean type data
abstract SharedPreferences.Editor putBoolean(String key, boolean value)
//Write float type data
abstract SharedPreferences.Editor putFloat(String key, float value)
//Write data of type int
abstract SharedPreferences.Editor putInt(String key, int value)
//Write long type data
abstract SharedPreferences.Editor putLong(String key, long value)
//Write data of String type
abstract SharedPreferences.Editor putString(String key, String value)
//Write data of type Set<String>
abstract SharedPreferences.Editor putStringSet(String key, Set<String> values)

Function: Used to complete data writing

Note that the call is completed through the Editor object of SharedPreferences

Parameters
key: the key corresponding to the specified data
value: specified value

3.4 remove() remove data

Function: Used to remove the data of the specified key

abstract SharedPreferences.Editor remove(String key)

Parameters
key: the key of the specified data

(TODO: What to do when the Key does not exist)

3.5 clear() Clear data

Function: Clear data (operate with caution)

3.6 commit() submits and saves data

3.7 getXxx() reads data

//Read all data
abstract Map<String, ?> getAll()
//The data read is of boolean type
abstract boolean getBoolean(String key, boolean defValue)
//The data read is of float type
abstract float getFloat(String key, float defValue)
//The data read is of int type
abstract int getInt(String key, int defValue)
//The data read is of long type
abstract long getLong(String key, long defValue)
//The data read is of String type
abstract String getString(String key, String defValue)
//The data read is of type Set<String>
abstract Set<String> getStringSet(String key, Set<String> defValues)

Parameters
key: the key of the specified data
defValue: The default value defValue used when the specified data cannot be read.

3. Basic use

1 An example

 /**
     * Save user information
     */
    private void saveUserInfo(){<!-- -->
        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = userInfo.edit();//Get Editor
        //After getting the Editor, write the data that needs to be saved
        editor.putString("username", "The cultivation of a cat");
        editor.putInt("age", 20);
        editor.commit();//Submit changes
        Log.i(TAG, "Save user information successfully");
    }
    /**
     * Read user information
     */
    private void getUserInfo(){<!-- -->
        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String username = userInfo.getString("username", null);//Read username
        int age = userInfo.getInt("age", 0);//Read age
        Log.i(TAG, "Read user information");
        Log.i(TAG, "username:" + username + ", age:" + age);
    }
    /**
     * Remove age information data
     */
    private void removeUserInfo(){<!-- -->
        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = userInfo.edit();//Get Editor
        editor.remove("age");
        editor.commit();
        Log.i(TAG, "Remove age data");
    }

    /**
     *Clear data
     */
    private void clearUserInfo(){<!-- -->
        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = userInfo.edit();//Get Editor
        editor.clear();
        editor.commit();
        Log.i(TAG, "Clear data");
    }

4. Monitoring

Listening when SharedPreferences is edited

SharedPreferences.OnSharedPreferenceChangeListener changeListener = new OnSharedPreferenceChangeListener() {<!-- -->
    @Override
    public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {<!-- -->
        //SharedPreferences instance where preferences are edited
        //The key corresponding to the edited entry in the SharedPreferences
    }
};
//userInfo registers to listen for events
userInfo.registerOnSharedPreferenceChangeListener(changeListener);
//userInfo logout listening event
userInfo.unregisterOnSharedPreferenceChangeListener(changeListener);

5. Performance analysis

ShredPreferences is a single instance object. After it is opened for the first time, there is no need to create it for subsequent acquisitions, and it is very fast.

When the data is obtained for the first time, the data will be loaded into a cached Map, and subsequent reads will be very fast.

Since it is an XML <-> Map storage method, the larger the data, the slower the operation. Get, commit, apply, remove, and clear will all be affected, so try to store the data as The function is split into several parts (that is, corresponding to the API in 3.1, and the name is passed in for differentiation).

Question:

  1. When is the MAP destroyed? Program exits?
  2. Does a name SharedPreferences correspond to a Map, or does the system maintain a unified Map?

6. Points of attention during use

1 Get SharedPreferences object

These methods and constants can be called directly in Activity

getSharedPreferences (String name, int mode)
getPreferences (int mode)
MODE_PRIVATE

And if it is not in Activity, such as in Service or other tool classes, it is obtained through the Context object:

context.getSharedPreferences (String name, int mode)
context.getPreferences (int mode)
Conetxt.MODE_PRIVATE

2 Data storage cycle

Saved SharedPreferences data will always exist unless it is overwritten, removed, cleared, or the file is deleted.

The data saved by SharedPreferences will be deleted when the app is uninstalled

Note that overwriting the installation (such as version update) will not delete or clear the SharedPreferences file

3 SharedPreferences is not strongly typed

(Strong typing here is a personal definition.)

That is, the value stored in SharedPreferences is not limited to type and is related to the latest overwrite write.

For example, the following two codes will cause the data with key age to be overwritten and updated.

case 1:

editor.putInt("age", 20);
//Overwrite the data with key age, the result is: age = 32
editor.putInt("age", 32);

// Passed at this time
sharedPreferences.getInt("age", 0) //The obtained value is:

case 2:

editor.putString("age", "20");
//Overwrite the data with key age, the result is: age = 32 (int type)
editor.putInt("age", 32);

// Passed at this time
sharedPreferences.getInt("age", 0) //The obtained value is:

sharedPreferences.getString("age", "0") //The obtained value is:

4 Runtime exception caused by inconsistent value types

The read key exists, but the type specified when reading does not correspond, a runtime exception will occur.

editor.putInt("age", 32);//Save as int type
String age = userInfo.getString("age", "null");//When reading, it is of String type and an exception occurs.

5 Functions that need to execute commit

// putXxx()
editor.putInt("age", 20);//Writing operation
editor.remove("age"); //Remove operation
editor.clear(); //Clear operation
editor.commit();//remember to commit
syntaxbug.com © 2021 All Rights Reserved.