Android-Droid
Android-Droid

Reputation: 14565

Android SharedPreferences issue

I need a little help with Android Shared Preferences. I'm trying to put a boolean type in SP and make it visible from every other activity in my application.And I want to be able to change the state of boolean type to true/false from another activity so I can make some changes in the UI depending on that boolean value. For now I'm using this piece of code,which I understand but it's not correct.

Here it is :

Activity 1:

boolean isLoggedIn = false;

        SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = isLogged.edit();
        editor.putBoolean("isLoggedIn", isLoggedIn);
        editor.commit();

Activity 2 :

        boolean isLogged=true;

        int mode = Activity.MODE_PRIVATE;
        SharedPreferences  mySharedPreferences;
        mySharedPreferences=getSharedPreferences("isLoggedIn",mode);
        mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
        boolean bool = mySharedPreferences.getBoolean("isLoggedIn",false);

        Log.w("Boolean","Boolean state : "+bool);

Upvotes: 0

Views: 1587

Answers (2)

Roll no1
Roll no1

Reputation: 1393

Put edit.commit(); after mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged); This will help you to get correct value.

Upvotes: 0

ingsaurabh
ingsaurabh

Reputation: 15269

In Activity 2 try using like this and it will work

mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

and remove below line

mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);

Upvotes: 3

Related Questions