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 Storing a Value in SharedPreferences

Chad Johnson
Chad Johnson
10,936 Points

Finally, save your changes with one of the appropriate methods!

SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

SharedPreferences.Editor editor = mSharedPreferences.edit().putInt("MeaningOfLife", 42).commit();

not sure what is wrong with my code, help please!

CodeChallenge.java
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

SharedPreferences.Editor editor = mSharedPreferences.edit().putInt("MeaningOfLife", 42).commit();

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

When you chain methods like that the value returned is what the end of the chain returns. According to the Android docs commit() returns a boolean, not a SharedPreferences.Editor. Instead you should split it into 2 lines.

SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("MeaningOfLife", 42).commit();