zocada

Using Shared Preferences to save data locally in Android

Persistent storage of data is necessary for almost all android application. From saving tiny bits of data to recognize the user to settings and preferences within the app. Android provides a consistent way of storing simple data in the internal storage privately for each application. In this article, we’ll look into how to store and retrieve data in android using SharedPreferences. SharedPrefs are intended to save Key-Value pairs in storage and Android doesn’t recommend saving confidential information in shared preferences without proper security. We’ll also look into a library which will help us to encrypt the data while saving locally.

Persistent storage of data is necessary for almost all android application. From saving tiny bits of data to recognize the user to settings and preferences within the app. Android provides a consistent way of storing simple data in the internal storage privately for each application. In this article, we’ll look into how to store and retrieve data in android using SharedPreferences. SharedPrefs are intended to save Key-Value pairs in storage and Android doesn’t recommend saving confidential information in shared preferences without proper security. We’ll also look into a library which will help us to encrypt the data while saving locally.

Shared Preferences

SharedPreferences API in Android provides required methods to save and retrieve small key-value paired data in android. The SharedPreferences class gives you an object which points to a local file which will be used to store the data through the API. These files are usually stored inside the App Data subdirectory of your application’s installation location. Android leverages the functionalities of XML to save these key-value pairs easily in these files. SharedPreferences files can be either private or shared among other applications.

Writing data into SharedPreferences

We’ll take a quick example of writing a username to SharedPreferences. First, we need to create an object of SharedPreferences with a Unique key which we’ll be using to save the data. Let’s call this PREFERENCE_FILE_KEY

private final String PREFERENCE_FILE_KEY = "myAppPreference";

It’s a good practice to store these key strings in strings.xml of your app and retrieve them using getString(R.string.preference_file_key) since these keys will remain same for accessing the saved data anywhere in your application.

1. Creating a SharedPreferences file

We can either create a new SharedPreference file or access an existing shared preferences file using the getSharedPreferences() with any Context in your App.

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);

In Kotlin, it’ll look like this

val sharedPref = activity?.getSharedPreferences(
        PREFERENCE_FILE_KEY, Context.MODE_PRIVATE)

2. Create a SharedPreferences Editor

To write data into the shared preferences, we need to use an object of `SharedPreferences.Editor` class.

Editor editor = sharedPref.edit();

3. Write and commit new data

We need to have a key to any data we enter into shared preferences. It’s a good practice to keep all your keys in strings.xm or creating a final variable in a shared static class.

private static final KEY_USERNAME = "prefUserNameKey"; //anything as u prefer
// ...
editor.putString(KEY_USERNAME, "My UserName");
editor.commit();

Alternatively, you can also use editor.apply() where the data is first written into the memory and then written into the storage asynchronously, editor.commit() directly writes to storage synchronously.
If you are using Kotlin, step 2 can be combined with 3 as below.

with (sharedPref.edit()) {
    putInt(KEY_USERNAME, "My UserName")
    commit()
}




Reading Data from SharedPreferences

We can use the getString() method in the SharedPreferences to read data from the saved preference file.

1. Open the SharedPreference file

Using the getSharedPreferences() with a Context, we can open an existing preference file by providing the KEY we used to create. In our case, it is the PREFERENCE_FILE_KEY variabe which holds the key.

SharedPreferences sharedPref = getActivity().getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);

In Kotlin:

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return

2. Read the data using SharedPreferences getters

There are numerous getters defined in SharedPreferences class to get the appropriate data you saved in preferences. We should use the getter which complies to the data type of the data we stored in the prefs. In our case, since the username is a String, we can use getString() method.

String username = sharedPref.getString(KEY_USERNAME, defaultValue);

Note that, we need to specify a defaultValue into the getters in case the data we are trying to retrieve does not exist, and the defaultValue will be used as a fallBack.

Encrypting SharedPreference Data using HAWK

Hawk is a handy library for Android which works similar to SharedPreferences but not quite similar to it. Hawk can encrypt your data before moving into the local storage, thus preventing from others accessing the data. This can be used to store confidential information into local storage by encrypting it. You can visit the official repository of HAWK to learn more about it.

1. Add Hawk to your app’s build.gradle

implementation "com.orhanobut:hawk:2.0.1"

2. Initialize Hawk

Hawk.init(context).build();

3. Read and Write data using Hawk

// To save data
Hawk.put(key, T);

// To read data
T value = Hawk.get(key);

// To delete a stored data
Hawk.delete(key);

// Check if a key exists
Hawk.contains(key);

// Count all the data stored
Hawk.count();

// Delete all the stored data
Hawk.deleteAll();




haxzie

Community Lead with a demonstrated history of working in a non-profit organization. Skilled in Python, Public Speaking, Graphic Design, Writing, and Android Development. Strong community and social services professional with a Bachelor's degree focused in Computer Science from Sahyadri College of Engineering and Management.