Android
SharedPreferences
Mobile Development
Data Storage
Android Development

How to use SharedPreferences in Android to store, fetch and edit values

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

SharedPreferences in Android

SharedPreferences is a key-value pair storage mechanism in Android used for storing small amounts of primitive data as long as the user interacts with the application. It is typically used to store user settings, app preferences, login credentials, or any small set of key-value data needed across application sessions.

Getting Started with SharedPreferences

To utilize SharedPreferences, you need to create or get an existing instance of a SharedPreferences object. Here's how you can do it:

java
SharedPreferences sharedPref = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

Here, "MyPreferences" is the name of the shared preferences file, and Context.MODE_PRIVATE is the operating mode that specifies the accessibility of this file. Using MODE_PRIVATE, the file can only be accessed by the application itself.

Storing Values

To store values in SharedPreferences, you need to use SharedPreferences.Editor. Here's a step-by-step process:

  1. Obtain the SharedPreferences instance.
  2. Get the Editor from the above SharedPreferences instance.
  3. Put value(s) using the editor.
  4. Apply or commit the changes.
java
1SharedPreferences.Editor editor = sharedPref.edit();
2editor.putString("username", "JohnDoe");
3editor.putInt("userAge", 25);
4editor.apply(); // or use commit()
  • apply() writes data to disk asynchronously and is recommended for non-blocking execution.
  • commit() writes data synchronously and returns boolean, indicating success or failure. It can block the execution.

Fetching Values

Fetching stored values is straightforward. You will use the get methods provided by the SharedPreferences class:

java
String username = sharedPref.getString("username", "defaultName");
int userAge = sharedPref.getInt("userAge", 0);

If the key doesn't exist, the method returns a default value provided by the user, such as "defaultName" for strings or 0 for integers.

Editing Values

You can modify the existing values using the same method for storing values. Simply call putX() for the key you want to update and apply the changes.

java
editor.putString("username", "JaneDoe");
editor.apply();

Removing Values

To remove specific entries, use remove() with the key name:

java
editor.remove("username");
editor.apply();

To clear all data, use the clear() method:

java
editor.clear();
editor.apply();

Modes

The Context.MODE constants control the access mode for shared preference files:

ModeDescription
MODE_PRIVATEFile is only accessible by the calling application.
MODE_WORLD_READABLE(Deprecated) Allows other applications to read but not write to the file.
MODE_WORLD_WRITEABLE(Deprecated) Allows other applications to read and write to the file.

Best Practices

  • Use apply() instead of commit() when possible to avoid UI lag.
  • Keep data stored in SharedPreferences small to keep performance optimal.
  • Use encryption for sensitive data before storing it.

Example Use Case

Below is a simple example demonstrating SharedPreferences usage in an Android Activity:

java
1public class MainActivity extends AppCompatActivity {
2
3    private SharedPreferences sharedPref;
4    private SharedPreferences.Editor editor;
5
6    @Override
7    protected void onCreate(Bundle savedInstanceState) {
8        super.onCreate(savedInstanceState);
9        setContentView(R.layout.activity_main);
10
11        sharedPref = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
12        editor = sharedPref.edit();
13
14        // Storing values
15        editor.putString("welcomeMessage", "Hello, Welcome!");
16        editor.apply();
17
18        // Fetching values
19        String welcomeMessage = sharedPref.getString("welcomeMessage", "Hi!");
20        Toast.makeText(this, welcomeMessage, Toast.LENGTH_LONG).show();
21    }
22}

Conclusion

SharedPreferences is a simple and effective way to handle persistent data storage for key-value pairs. It is preferable for smaller pieces of data but should be used judiciously to avoid affecting application performance. For larger data sets, consider using a database solution like SQLite.

By following the provided methods and best practices, you will efficiently manage application state and user preferences in your Android application using SharedPreferences.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms