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

Zubeyr Aciksari
Zubeyr Aciksari
21,074 Points

Ack! There is an error regarding SharedPreferences in the code below. Fix it such that "MeaningOfLife" is properly store

Hi, can someone please show me where the bug is? Thanks!

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

George Pirchalaishvili
George Pirchalaishvili
3,747 Points

Well first of all, you need to return a number - int, rather than String :) Secondly, check documentation regarding the "put" methods ;):

http://developer.android.com/reference/android/content/SharedPreferences.html

Daniel Hartin
Daniel Hartin
18,106 Points

Hi Zubeyr

I don't want to give you the exact answer as I think you will benefit greatly from figuring it our for yourself however, concentrate on the method below (HINT: check the data types)

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


  }

Hope this helps

Daniel

Zubeyr Aciksari
Zubeyr Aciksari
21,074 Points

Thanks a lot guys, it worked!