Search code examples
androidcheckboxandroid-activitypreferences

Get Value of a CheckBoxPreference in an Activity


I've got a preferences.xml:

    <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory 
        android:title="Category">
        <CheckBoxPreference 
            android:key = "inputPreferences" 
            android:title = "Title" 
            android:summary = "Subtitle"/>
    </PreferenceCategory>
</PreferenceScreen>

I want to read out the value of the CheckBoxPreference, and depending on it, there sould be shown (for example) a TextView. I tried following code, but it doesn't work:

@Override
protected void onResume() {
 // TODO Auto-generated method stub
 super.onResume();
 Toast.makeText(this, "onResume", Toast.LENGTH_LONG).show();

 SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
 if(myPreference.getBoolean("checkbox", false)) {
      VarText.setVisibility(View.VISIBLE);
      VarText.setText("foo");
 }

}

Hope anyone can help, thanks :)


Solution

  • you need to be using the key attribute that you set in your xml file. Change the android:key to "checkbox" rather than "inputPreferences"