SharedPreferences stores small amounts of application configuration data

SharedPreferences are a simple way in Android to store small amounts of application configuration data. SharedPreferences is a mechanism for lightweight data storage on the Android platform. It provides simple methods to save and get basic types of data, such as boolean, float, int, long and string.

Note: SharedPreferences does not support storing large amounts of data, nor does it support complex data types. If you need to store larger amounts of data, or need to store complex data types, you may want to consider using a SQLite database or file storage.

Applicable scenarios:

  1. Application configuration information storage: SharedPreferences can be used to store application configuration information, such as user preferences, user interface state, application preferences, etc.
  2. User login status management: You can use SharedPreferences to store user login status (for example, remember me option) to keep the user logged in across application restarts.
  3. Local storage of small amounts of data: SharedPreferences is a convenient choice if you need to save small amounts of data in your application, such as user-set preferences or temporary data.

View SharedPreferences in Android studio development tools:

Find the Device Explorer function. The icon is a mobile phone + a magnifying glass. Find it according to the directory: data/data/package name/shared_prefs/various file names defined by yourself , open it and the data you want will be stored there.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <int name="score" value="100" />
    <boolean name="isLoggedIn" value="true" />
    <string name="username">John</string>
</map>

Errors encountered when downloading or opening: There were errors downloading files and/or directories: ‘secure_mkdirs failed: Operation not permitted’ error on device serial #emulator-5554 executing service ‘sync-send(‘/data/local/tmp/device -explorer/.temp_cp_test_file.tmp’)’This error message indicates that when executing the service on the device emulator (emulator-5554), the directory cannot be created and the file cannot be downloaded. The specific error message is “secure_mkdirs failed: Operation not permitted”, which means that an error of insufficient permissions occurred when creating the directory.

Try the solution:
Use the command line to enter in the platform-tools directory to complete the following operations. If adb does not exist, add the platform-tools directory to the system environment variable path. After completing the following operations, restart Android Studio and it should be fine.

D:\androidSDK\canary\platform-tools>adb shell
generic_x86_arm:/ $ su
generic_x86_arm:/ # chmod 777 /data
generic_x86_arm:/ # adb root
/system/bin/sh: adb: not found
127|generic_x86_arm:/ #

Basic steps for using SharedPreferences:

  1. Get SharedPreferences instance: First, get a SharedPreferences object, usually using the getSharedPreferences method, where the first parameter is the file name, and the second parameter is the access mode (usually using MODE_PRIVATE, if you want to know what other access modes are, see below).
SharedPreferences sharedPreferences = getSharedPreferences("The file name you defined", MODE_PRIVATE);
  1. Write data: Use the SharedPreferences Editor to write data. You can get an editor using the edit() method, and then use different putX() methods (such as putString(), putInt(), putBoolean(), etc.) to store data.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "John");
editor.putInt("score", 100);
editor.putBoolean("isLoggedIn", true);
editor.apply(); // Submit changes
  1. Reading data: SharedPreferences instances make it easy to read stored data.
String username = sharedPreferences.getString("username", "");
int score = sharedPreferences.getInt("score", 0);
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);

Note:

  1. Don’t abuse: SharedPreferences are suitable for storing small amounts of data, not suitable for large amounts of data storage. For large data sets, other storage mechanisms such as databases should be used.

  2. Sensitive data storage: Do not store sensitive information (such as passwords or keys) in SharedPreferences because they can be accessed relatively easily. For sensitive data, secure storage should be used, such as Android’s EncryptedSharedPreferences.

  3. Asynchronous commit: Use the apply() method to asynchronously commit changes instead of the commit() method to avoid blocking the main thread.

  4. Clear data: Use the clear() method to clear all data stored in SharedPreferences.

editor.clear().apply(); // Clear all data
  1. Consider data versioning: If your application’s data structure changes, be careful to handle data migration and versioning.

  2. Context management: When obtaining a SharedPreferences object, make sure to provide the correct context to ensure access to the correct SharedPreferences file.

  3. Backup and Restore: By default, SharedPreferences data is not automatically backed up to the cloud. If you need to back up and restore data, you need to implement your own logic or use the Auto Backup feature.

In short, SharedPreferences is a lightweight local storage mechanism suitable for persistence and configuration management of small amounts of data. But use it with caution, avoid storing sensitive information, and pay attention to data versioning and backup and recovery strategies.

SharedPreferences object access mode

Access mode constants Access permission values Description
MODE_PRIVATE 0 Default mode, only the current application can access the file.
MODE_WORLD_READABLE (deprecated) 1 Other applications can read the data of this file, and its use is no longer recommended .
MODE_WORLD_WRITEABLE (deprecated) 2 Other applications can write or modify the file’s data, no longer Recommended.
MODE_MULTI_PROCESS 4 The file can be accessed even if the application is running in multiple processes.
  1. MODE_PRIVATE (0): This is the default access mode, which means that only the current application can access the SharedPreferences file. Other applications cannot access this data.
  2. MODE_WORLD_READABLE (1): Obsolete access mode, no longer recommended. Indicates that all applications can read the data in this SharedPreferences file. This mode is a security risk and is not recommended.
  3. MODE_WORLD_WRITEABLE (2): Obsolete access mode, no longer recommended. Indicates that all applications can write or modify the data in this SharedPreferences file. This mode is a security risk and is not recommended.
  4. MODE_MULTI_PROCESS (4): Indicates that multiple processes can access the same SharedPreferences file at the same time. This can be used in some cases to ensure that shared data is correctly accessed and updated between multiple processes.

These access modes are often used with the getSharedPreferences method to determine access permissions for SharedPreferences files. For example:

javaCopy code
SharedPreferences sharedPreferences = getSharedPreferences("my_preferences", MODE_PRIVATE);

In the above example, using the MODE_PRIVATE access mode creates a SharedPreferences file that is only accessible to the current application. Typically, you would use MODE_PRIVATE to ensure that only your application can access this data. The use of other modes is no longer recommended as they may introduce security issues.

Solution to a small question: Why is the access permission value 0124 but not 3?

**Answer:** In Android, the access mode of SharedPreferences is represented by integer values. These integer values are composed of bit masks (bitmask), and each bit represents a different access permission. These integer values are usually powers of 2 because they can be represented in a binary representation with only one bit being 1 and the other bits being 0.

  • MODE_PRIVATE corresponds to the integer value 0. In the binary representation, only the first bit is 1, and the other bits are 0.
  • MODE_WORLD_READABLE corresponds to the integer value 1. In the binary representation, only the second bit is 1, and the other bits are 0.
  • MODE_WORLD_WRITEABLE corresponds to the integer value 2. In the binary representation, only the third bit is 1, and the other bits are 0.
  • MODE_MULTI_PROCESS corresponds to the integer value 4. In the binary representation, only the fourth bit is 1, and the other bits are 0.

This bitmask is designed to allow you to combine different access rights. For example, if you want to enable MODE_MULTI_PROCESS on top of MODE_PRIVATE, you can add their values together, That is, 0 + 4 = 4, which means that both MODE_PRIVATE and MODE_MULTI_PROCESS are enabled.

So, due to this design, although there is no access mode with integer value 3, you can achieve a similar effect by combining other modes, setting the corresponding bits as needed.