Calling SharedPreferences using application context.

Ariel Silva
1 min readApr 7, 2018

--

If you wish not to pass context from your activity going to your Presenters and ViewModels when saving or retrieving your key-value data from SharedPreferences this might help you.

In your Application context:

public class MyApplication extends Application {

private static Context context;

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

public static Context getContext() {
return context;
}
}

Usage:

PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());

I created a sample SharedPreferenceData class where you can save and retrieve your key-value data.

public class SharePreferenceData {

private static final String TOKEN = "token";

private SharedPreferences sharedPreferences;

public static SharePreferenceData getInstance() {
return new SharePreferenceData();
}

private SharePreferenceData() {
this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
}

public void saveToken(final String token) {
sharedPreferences.edit().putString(SharePreferenceData.TOKEN, token).apply();
}

public String getToken() {
return sharedPreferences.getString(SharePreferenceData.TOKEN, StringUtils.EMPTY);
}
}

Don’t forget to modify your AndroidManifest.xml file:

<application
android:name=".MysApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"/>

To learn more about SharedPreferences visit this link.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ariel Silva
Ariel Silva

Written by Ariel Silva

Tech Lead | Product Design | Digital Innovation

No responses yet

Write a response