22 Boxes logo

Better Shared Preferences

April 09, 2020

Image from instagram

Shared preferences are the goto solution for storing almost any kind information for your android app.

But implementing them can be cumbersome and verbose at times, initializing the shared preferences object every time you want to read/edit them.

Here is an alternate approach to use shared preferences easily and effectively:

  • We create a Prefs class which will act as the only point of contact for reading/writing our shared preferences:
public class Prefs implements PrefsContract {
    public static SharedPreferences prefs;
    public static SharedPreferences.Editor editor;

    public Prefs() {
        prefs = BaseApplication.getContext().getSharedPreferences("MyApplication", Context.MODE_PRIVATE);
        editor = prefs.edit();
    }

    @Override
    public boolean isFirstTimeLaunch() {
        return prefs.getBoolean(PrefsContract.isFirstTimeLaunch, true);
    }

    @Override
    public void setFirstTimeLaunch(boolean firstTimeLaunch) {
        editor.putBoolean(PrefsContract.isFirstTimeLaunch, firstTimeLaunch).commit();
    }
}

“My Application” is the shared preferences name. It can be a string with your application name.

We’re implementing an interface here that holds all the shared preferences that are used in your app.

Though this is completely optional but this method helps you to know which are the fields you have stored in your shared preferences and prevents your shared preferences data from getting out of hand.

public interface PrefsContract {
    String isFirstTimeLaunch = "isFirstTimeLaunch";

    boolean isFirstTimeLaunch();

    void setFirstTimeLaunch(boolean firstTimeLaunch);
}


  • Now that our Prefs class is defined, all we need is the context to initialize our shared preferences object. This context needs to be application wide and not tied to any one activity, so we create an Application class and set its context from our application manifest. We create this class as a singleton because we only ever need a single instance of it at any time.

The application singleton class:

public class BaseApplication extends Application {
    public static Context context;
    public static BaseApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        instance = this;
    }

    public static BaseApplication getInstance() {
        return instance;
    }

    public static Context getContext() {
        return context;
    }

}


  • And in our application AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.yourpackage.yourapp">

    <application
        android:name=".BaseApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_logo"
        android:label="@string/app_name"
        android:roundIcon="@drawable/ic_logo_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Notice the android:name=“.BaseApplication” part in application tag

That’s it!

Now you can use your preferences like:

public class MainActivity extends BaseActivity {

    Prefs prefs = new Prefs();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(prefs.isFirstTimeLaunch()){
            //Do something.
        }
    }
}

You can even put the Prefs object in your base activity so that you don’t have to initialize it again and again.


Written by Gagandeep Rangi who likes to talk about himself in third person. Twitter Instagram

Email icon