Wednesday, July 29, 2020

Using Shared Preferences to save data locally in Android

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.
Using Shared Preferences to save data locally in Android

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";

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

No comments:

Post a Comment