📅  最后修改于: 2023-12-03 14:39:08.342000             🧑  作者: Mango
SharedPreferences is a simple key-value store to save small amounts of data in Android. We can store primitive data types such as bool, float, int, long, and string values in SharedPreferences. In this guide, we will cover the following topics:
We can create SharedPreferences object using getSharedPreferences method of Context class. It requires two parameters: the name of the SharedPreferences and the access mode. The access mode determines who can access the SharedPreferences. The three access modes are:
Here's an example:
SharedPreferences sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
To write to SharedPreferences, we need to edit it using SharedPreferences.Editor. We can get an editor object using the edit method of SharedPreferences. We can then use put methods of the editor object to set key-value pairs.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "johndoe");
editor.putBoolean("isLoggedIn", true);
editor.apply();
To read from SharedPreferences, we can use the get methods of SharedPreferences. If the key doesn't exist, it returns a default value.
String username = sharedPreferences.getString("username", "");
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
To update SharedPreferences, we can simply use the put methods again with the updated values.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "janedoe");
editor.apply();
To delete SharedPreferences, we can use the remove method of SharedPreferences.Editor. To delete all SharedPreferences, we can use the clear method.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("username");
editor.apply();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
SharedPreferences is a useful tool to store small amounts of data in Android. However, it's important to note that SharedPreferences is not suitable for storing large amounts of data or sensitive information. In those cases, we should use other options such as SQLite, internal storage, or external storage.