Groosha
Groosha

Reputation: 3067

Can't get SharedPreferences with activity

Sorry for my bad English.
On my application, I save token (it's a web app) in shared preferences. In first activity I do this:

(token = 123)
SharedPreferences sp = getPreferences(MODE_PRIVATE);
Editor ed = sp.edit();
ed.putString("token", Main.getToken()); 
ed.commit();
Log.d("Recieved token: ", sp.getString("token", "null")); // Recieved token: 123

As you see, shared prefs are saved.
I have another activity, which may be called from browser to share link.
Code:

sp = getPreferences(MODE_PRIVATE);
Log.d("Token recieved: ", sp.getString("token", "null")); // null

But on another activity shared prefs return null. What can I do?

Upvotes: 1

Views: 3467

Answers (2)

NigelK
NigelK

Reputation: 8490

To explain the reason why getPreferences() didn't work for you:

When you call getPreferences() without specifying a Shared Preferences name, it returns a Shared Preference using the calling Activity's class name as the Shared Preference name. That's why you are getting null in your other activity - it's actually a different Shared Preference set that you are referring to.

Use getSharedPreferences instead, using whatever preferences name you like:

getSharedPreferences("my_prefs", Activity.MODE_PRIVATE);

That will then be available throughout your application. However using getPreferences() is suitable where you don't need to refer to the data stored outside of a particular Activity.

Upvotes: 8

user1831682
user1831682

Reputation:

use like following,,

SharedPreferences mAppSettings = getSharedPreferences("SharedPref", MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = mAppSettings.edit();
        prefEditor.putString(""token, "");
        prefEditor.commit();

for retrieving,,,

final SharedPreferences mAppSettings1 = getSharedPreferences(
                "SharedPref", MODE_PRIVATE);
             String token= mAppSettings1.getString("token", "");

Upvotes: 1

Related Questions