📜  android sharedpreferences - Java (1)

📅  最后修改于: 2023-12-03 14:39:08.342000             🧑  作者: Mango

Android SharedPreferences

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:

  1. Creating SharedPreferences
  2. Writing to SharedPreferences
  3. Reading from SharedPreferences
  4. Updating SharedPreferences
  5. Deleting SharedPreferences
Creating SharedPreferences

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:

  • MODE_PRIVATE - only this app can read and write
  • MODE_WORLD_READABLE - any app can read, but only this app can write
  • MODE_WORLD_WRITEABLE - any app can write, but only this app can read

Here's an example:

SharedPreferences sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
Writing to SharedPreferences

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();
Reading from SharedPreferences

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);
Updating SharedPreferences

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();
Deleting SharedPreferences

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.

Markdown代码块结束