Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using shared preferences in between activities

I am trying to share a shared preference in between two activities of my project, but for some reason I am not able to pass the data.

I have Activity A which reads the shared preference and Activity B that reads as well as edit that shared preference.

Here is the code I am using to write the shared preference in Activity B:

SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.
    MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("theme", "black");
editor.commit();

and for reading in Activity A:

SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.
    MODE_WORLD_WRITEABLE);
String theme=sharedPref.getString("theme","blue");

I have tried using the different modes, and it worked in Activity B in PRIVATE mode but it wasn't shared to activity A. For some reasons I think I have two different shared preferences(same name) for the two different activities. How do I use the same shared preference for both the activities ?

like image 885
Tanuj Wadhwa Avatar asked Jan 27 '26 18:01

Tanuj Wadhwa


1 Answers

You can do simpler - in any activity:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

You will have the same prefs this way from anywhere.

http://developer.android.com/reference/android/preference/PreferenceManager.html#getDefaultSharedPreferences(android.content.Context)

like image 59
Alexander Kulyakhtin Avatar answered Jan 29 '26 06:01

Alexander Kulyakhtin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!