poster

Shared Preferences in Android (Java)

Hey folks đź‘‹ !

In this post, you will learn about SharedPreferences in detail. It will give you kick start to use if you never heard or implemented shared preferences ever before. There are some scenarios where you want to display AlertDialog Box or Activity or Fragment once since after the user install the app. For example a Walkthrough Guide like this one :

Walkthrough or guide.

Ever come across 🤔 how this is being achieved or implement. Well there are two possible solution first is Data Store and another one is Shared Preferences. In this post we will learn about shared preferences.

Well, What exactly SharedPreferences is…

SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.

. It is an interface.

Google Developer Page

Android Shared preferences are used to store data in key and value pair so that we can retrieve the value on the basis of key. It is is used to store and retrieve primitive information. In android, string, integer, long, number etc. are considered as primitive data type. Shared preferences allow you to store small amounts of primitive data as key/value pairs in a file on the device.

Shared Preferences

Advantages of SharedPreferences :

  1. Data in a saved activity instance state is retained across activity instances in the same user session.Shared preferences persist across user sessions.
  2. Shared preferences persist even if your app stops and restarts, or if the device reboots.

Let’s see a simple example of android shared preference. Consider the same scenario, we want the user, who just install our app, to know about features of our app.

Creating a shared preferences file

In this example, You need only one shared preferences file for your app, and it is customarily named with the package name of your app. This makes its name unique (you can name anything, but conventionally is it package name of your app) and easily associated with your app. It is recommended to create shared preferences in onCreate() method in the mainActivity like launcher/Splash Screen and store it in member variable.

private String sharedPrefFile = "com.amanthebreaker.sharedPrefExample.mySharedPrefs";
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);

What are the modes here ?

The mode defines who has access to your app’s preferences i.e No other app would be able to access that file.

In simple terms:

  • MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application.
  • In MODE_WORLD_READABLE other application can read the created file but can not modify it.
  • In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.

But MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE are deprecated due to some security issues.

Saving the shared Preferences

It is recommended to save shared preferences as per the need but here as per our aim we use life cycle’s onPause() method. Shared preferences are saved using SharedPreferences.Editor interface and this editor take care all the operation that you want to perform. But first we need to get the shared Preference :

SharedPreferences.Editor preferencesEditor = mPreferences.edit();

After getting the instance of editor, remember we save shared preference as key/value pair and to do that we use methods like putInt() or putString() If there’s existing any previous value it get overright.

preferencesEditor.putInt("firstTimer", 1);

Final to get changes saved we need to commit() or apply(), we won’t go into to much details. It is recommended to apply() the changes. Remember last commit() or apply() decides what is saved.

preferencesEditor.apply();

Final codes in onPause() method :

@Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putInt("firstTimer", 1);
preferencesEditor.apply();
}

Restoring shared preferences

Generally shared preferences are restored in onStart() method and onCreate() method. The “get” methods such as getInt() or getString() take two arguments—one for the key and one for the default value if the key cannot be found. Using the default argument, you don’t have to test whether the preference exists in the file.

firstTime = mPreferences.getInt("firstTime", 1);
        if (firstTime == 1) {
                SharedPreferences.Editor editor = mPreferences.edit();
                AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                builder1.setMessage("Welcome to Shared Prefs App! \nthis AlertDialog would appear once " +
                        "after installation of this App. On next launch this Dialog box won't appear.");
                builder1.setCancelable(true);

                builder1.setPositiveButton(
                        "ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

                AlertDialog alert11 = builder1.create();
                alert11.show();

                editor.apply();
            }

Clearing shared preferences :

SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putInt("number", 42);
preferencesEditor.clear();
preferencesEditor.apply();

So we have just learnt basic features of sharedpreferences, though data store has lots of benefits over SharedPreferences, SharedPreferences is one of the best choice to save key/value based data. Remember You should only use SharedPreferences to store small bits of data related to user configuration. It can only store basic data types, so if you have more complex bits of information, you should probably switch to another mechanism like Data Store.

Here’s the link of complete source code of the example here.

Some references and resource you should visit after this post :

  1. https://stackoverflow.com/questions/18834193/use-sharedpreference-to-define-drawable-resources
  2. https://scalereal.com/android/2020/09/03/hello-datastore-bye-sharedpreferences-android.htm
Posts created 4

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top