Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Diego Marrs
8,243 PointsStuck 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
Full Stack JavaScript Techdegree Graduate 22,610 PointsWhy 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
9,191 PointsRyan Lentz
9,191 PointsThe first solution works. The second recommendation won't work because the value of mCheckBox should remain true if it was already true.