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 Troubleshooting SharedPreferences

Were is the Bug.......

Ack! There is an error regarding SharedPreferences in the code below. Fix it such that "MeaningOfLife" is properly stored and retrieved as an int value.

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

  protected SharedPreferences mSharedPreferences;

  public void onCreate(Bundle savedInstanceState) {

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Some code omitted!

  public int getMeaningOfLife() {
    return mSharedPreferences.getInt("MeaningOfLife", 42);

  public void setMeaningOfLife() {
        .putString("MeaningOfLife", "42")   // 42 should be an int not a String

2 Answers

Yep - this line of code needs to change in two places:

.putString("MeaningOfLife", "42")

The 42 is being a string, and the method is used for Strings too. It needs to be:

.putInt("MeaningOfLife", 42)

So, change the method and remove the double quotes.


I've added a comment showing where the problem is. ;-)


is 42 not the int i still cant get it