简体   繁体   中英

How can I CHANGE shared preferences values from another activity?

I got a few activities and one called SettingsActivity . I've created shared preferences there (just one Boolean value for now, but it'll be more).

I want to store values in there and access (not only access but actually change) the values of it in all of my other activities. How can I change this Boolean value from other activity?

Thank you so much!!!

When you have created a SharedPreference , its already available in all other activities for being accessed from them.

I hope while you are saving this, you are doing something like the following.

private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.edit().putBoolean("SOME_KEY", booleanValue).apply();

Now when you are getting it from another activity you need to do something like the following.

private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.getBoolean("SOME_KEY", defValue);

SharedPreference stores key-value pair and hence you can find the value against the key wherever you want to get it.

Now you can change it from any activity. Just use the same key for referencing it from other activities.

private SharedPreferences prefs;
prefs = getSharedPreferences("YOUR_APP_NAME", Context.MODE_PRIVATE);
prefs.edit().putBoolean("SOME_KEY", otherBooleanValue).apply();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM