Android: Storing, Retrieving & Editing Values with SharedPreferences

Android provides a way to store and retrieve key-value pairs using the SharedPreferences API. This is a simple and efficient way to persist data across app sessions without the need for a database or file storage.

Índice
  1. Storing Values
  2. Retrieving Values
  3. Editing Values

Storing Values

To store a value, you first need to get an instance of the SharedPreferences class:


SharedPreferences preferences = getSharedPreferences("myPrefs", MODE_PRIVATE);

The first parameter is the name of the preferences file, and the second parameter is the mode, which determines the accessibility of the preferences file.

Once you have a SharedPreferences instance, you can use its edit() method to obtain an instance of the Editor class:


SharedPreferences.Editor editor = preferences.edit();

The Editor class provides methods for adding key-value pairs:


editor.putString("name", "John");
editor.putInt("age", 30);
editor.putBoolean("isMarried", true);

Finally, you need to commit the changes:


editor.commit();

Retrieving Values

To retrieve a value, you just need to call the appropriate method on the SharedPreferences instance:


String name = preferences.getString("name", "");
int age = preferences.getInt("age", 0);
boolean isMarried = preferences.getBoolean("isMarried", false);

The second parameter of each method is the default value to use if the key is not found in the preferences file.

Editing Values

To edit a value, you can simply call the appropriate put method with the new value, followed by a commit:


editor.putString("name", "Jane");
editor.commit();

Note that you must call commit() to save the changes.

In conclusion, SharedPreferences provide a simple and efficient way to store and retrieve key-value pairs in Android. By using this API, you can easily persist data across app sessions without the need for a database or file storage.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information