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

I could use some help on troubleshooting sharedpreferences code challenge. I am not sure were the error is. Please help?

I have been working on this for the past 30 minutes, I don't know where the error is pleas help ?

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

public class MainActivity extends Activity {

  protected SharedPreferences mSharedPreferences;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Some code omitted!
  }

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

  public void setMeaningOfLife() {
    mSharedPreferences
        .edit()
        .putString("MeaningOfLife", "42")
        .commit();
  }
}

3 Answers

Jack Middlebrook
Jack Middlebrook
19,746 Points

In setMeaningOfLife notice how it is .putString("MeaningOfLife", "42") think of how you might change this line so that an int is stored instead...

Thank you so much I just look over things like that on accident.

I cannot figure it out. Can you explain further?

Jack Middlebrook
Jack Middlebrook
19,746 Points

Hey Eden, Currently the code has putString("MeaningOfLife", "42") which stores a String "42" for the key "MeaningOfLife". You need to fix it so that it the key "MeaningOfLife" stores an int. To do this you need to change two things. First, instead of using putString you need to use putInt. Just changing to putInt will still give you an error because the second parameter needs to be an int. For this you need to change "42" to be an int value so remove the quotation marks around 42. You can read more about putInt in the docs [here](http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#putInt(java.lang.String, int). Hope that helps.

Thank you for explaining. Really appreciate your help.