info@androidpaper.co.in

Shared Preferences in Android with Example

Android Shared Preferences is a simple key-value storage mechanism provided by the Android framework. It allows you to store and retrieve small amounts of data persistently across application launches. Here's how you can use Android Shared Preferences to store and retrieve key-value pairs:

Create or Retrieve SharedPreferences Object:
To use SharedPreferences, you need to obtain an instance of the SharedPreferences class. You can do this by calling the getSharedPreferences() method in your Activity or Application context:

SharedPreferences sharedPreferences = getSharedPreferences("my_preferences", Context.MODE_PRIVATE);

In the above example, "my_preferences" is the name of the SharedPreferences file. Use a unique name for each SharedPreferences file you create.

Storing Data:
To store a key-value pair, you can use the SharedPreferences.Editor object obtained from the SharedPreferences instance. Use the put methods to store different data types:

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("key_string", "Hello, World!");
editor.putInt("key_int", 42);
editor.putBoolean("key_boolean", true);
// Add more key-value pairs if needed
editor.apply();  // or editor.commit() for immediate write (synchronous)

In the above example, we store a string, an integer, and a boolean value. You can use other put methods to store different data types like float or long.

Retrieving Data:
To retrieve the stored values, you can use the appropriate getter methods:

String stringValue = sharedPreferences.getString("key_string", "");
int intValue = sharedPreferences.getInt("key_int", 0);
boolean booleanValue = sharedPreferences.getBoolean("key_boolean", false);
// Retrieve other values as needed

In the above example, the second parameter in the getter methods represents the default value to be returned if the key is not found in the SharedPreferences.

Removing Data:
If you want to remove a specific key-value pair, you can use the remove() method:

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("key_string");
editor.apply();

Clearing All Data:

If you want to clear all the data stored in the SharedPreferences, you can use the clear() method:

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();

Another Written Description

Remember to apply or commit the changes made to the SharedPreferences using apply() or commit() respectively.

Using Android Shared Preferences, you can easily store and retrieve small amounts of data persistently in your application. It is suitable for storing user preferences, settings, and other similar data. However, for large amounts of structured or complex data, other data storage mechanisms like SQLite or file storage may be more appropriate.