Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Android Activity Lifecycle The Project Implementing SharedPreferences

firnaz luztian adiansyah
firnaz luztian adiansyah
5,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

2 Answers

aakarshrestha
aakarshrestha
6,509 Points

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!

Happy coding!

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");