botbot
botbot

Reputation: 7359

Where is the best place to store globals (auth token) in Android

I'm pretty new to android. I want to know where the best place is to store something like a auth token that I get from logging in on my server. With every subsequent request, I will have to post this auth token. Sure I could keep a global class somewhere, but I just want to know what a good / standard way is to store data that persists across activities and intents. Thanks!

Upvotes: 9

Views: 6349

Answers (1)

Mine
Mine

Reputation: 4241

SharedPreferences is the way to go. See doc here: https://developer.android.com/reference/android/content/SharedPreferences.html

Some example code is like below.

To save the token:

SharedPreferences settings = PreferenceManager
                            .getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString(some_key, your_auth_token_string);
editor.commit();

To get the token:

SharedPreferences settings = PreferenceManager
                            .getDefaultSharedPreferences(context);
String auth_token_string = settings.getString(some_key, ""/*default value*/);

Upvotes: 14

Related Questions