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 Activity Lifecycle Introducing SharedPreferences Saving and Retrieving Data with SharedPreferences

Diego Marrs
Diego Marrs
8,243 Points

Stuck on challenge 4/4

Hello

I'm having trouble passing this challenge, i'm doing what it tells me to do but it still tells me that the CheckBox object needs to return 'false':

import android.view.View;
import android.os.Bundle;

public class MainActivity extends Activity {
  private static final String PREFS_FILE = "com.sharedpreferencesapp.preferences";
  private static final String KEY_CHECKBOX = "KEY_CHECKBOX";
  public CheckBox mCheckBox;

  private SharedPreferences mSharedPreferences;
  private SharedPreferences.Editor mEditor;

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

    mCheckBox = (CheckBox) findViewById(R.id.checkBox);
    mSharedPreferences = getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
    mEditor = mSharedPreferences.edit();

    if (mSharedPreferences.getBoolean(KEY_CHECKBOX, true)) {
      mCheckBox.setChecked(true);
    } else if (mSharedPreferences.getBoolean(KEY_CHECKBOX, false)) {
      mCheckBox.setChecked(false);
    }
  }

  @Override
  protected void onPause() {
    super.onPause();

    mEditor.putBoolean(KEY_CHECKBOX, mCheckBox.isChecked());
    mEditor.apply();
  }
}

Please help!

1 Answer

Judah Devasahayam
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Judah Devasahayam
Full Stack JavaScript Techdegree Graduate 22,610 Points

Why are you using else if? just use if else and your code should look like this

 if (mSharedPreferences.getBoolean(KEY_CHECKBOX, false)) {
      mCheckBox.setChecked(true);
    } else {
      mCheckBox.setChecked(false);
    }

or just use 

mCheckBox.setChecked(mSharedPreferences.getBoolean(KEY_CHECKBOX, false));
Ryan Lentz
Ryan Lentz
9,191 Points

The first solution works. The second recommendation won't work because the value of mCheckBox should remain true if it was already true.