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 Data Persistence Key-Value Saving with SharedPreferences Reading a Value from SharedPreferences

Zubeyr Aciksari
Zubeyr Aciksari
21,074 Points

A superior alien race will spare Planet Earth if we can provide the Answer to the Ultimate Question of Life, the Univers

Please help, i am just stuck in here! Thanks!

"A superior alien race will spare Planet Earth if we can provide the Answer to the Ultimate Question of Life, the Universe, and Everything. Get the answer you just stored in SharedPreferences using the key "MeaningOfLife"! Store it in the answer variable provided, using whatever value you want as the default."

CodeChallenge.java
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
   SharedPreferences mSharedPreferences = new answer("MeaningOfLife") ;
int answer;

3 Answers

George Pirchalaishvili
George Pirchalaishvili
3,747 Points

You already have SharedPreferences, so you do not need to create it again.

SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); // you create instance of SharedPreferences storage

mSharedPreferences.edit().putInt ("MeaningOfLife", 11); // You add number 11 (ultimate answer) to your storage and mark it with MeaningOfLife tag (so it is easier to get access to it later on)
int answer = mSharedPreferences.getInt ("MeaningOfLife", null); // you try to get Int from preferences with tag MeaningOfLife
Ian Z
Ian Z
14,584 Points

this does not work, the null has to be set to any number, null causes the method to cause a compiler error

SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

mSharedPreferences.edit().putInt ("MeaningOfLife", 11); int answer = mSharedPreferences.getInt ("MeaningOfLife", 11);

this gives no errors Ian Z

Zubeyr Aciksari
Zubeyr Aciksari
21,074 Points

Thanks a lot George, this helped!

George Pirchalaishvili
George Pirchalaishvili
3,747 Points

no problem ;) updated answer to make it more readable