Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
firnaz luztian adiansyah5,295 Points
how to retrieve a stored SharedPreference value from mainActivity to a different activity?
From the example app we were able to save and retrieve the input value from our edittext from main activity.
But how do we retrieve the stored shared preference in a different activity? help I'm stuck
Lets say you have stored the value in sharedPreferences. Now you want to go from MainActivity.java to NextActivity.java (Just an example).
In NextActivity.java class, you need to get the sharedPreferences in such a way:
SharedPreferences sharedPreferences = getSharedPreferences(SHAREDPREFERENCES, 0); String name = sharedPreferences.getString(USERNAMEKEY, "Not found!");
SHAREDPREFERNCES = value of the sharedprefences you have when first creating the preference to store the value. USERNAMEKEY = it is the key to the value.
Now the store value of sharedpreference is in the string called "name".
Hope it helps!
The easy way is like this (Works in any activity):
Save to preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPrefererences(this); SharedPreferences.Editor editor = preferences.edit(); editor.putString("key","value"); editor.apply();
Retrieve a Preference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String value = preferences.getString("key", "defaultValue");