javaandroidbuttoncheckboxpreference

Failed to query value from Android Checkbox Preference


I have two activity below. See my code...

SettingsActivity.java

public class  SettingsActivity extends AppCompatPreferenceActivity {

static CheckBoxPreference checkBoxPreference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
    checkBoxPreference = (CheckBoxPreference)findPreference("checkPref");
    setupActionBar();
}

private void setupActionBar() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

}

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                if (SettingsActivity.checkBoxPreference.isChecked()){
                    Toast.makeText(MainActivity.this, "Checked", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Not Checked", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e){
                Toast.makeText(MainActivity.this, "Failed to query", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

}

As I have used Try-Catch here so, it is not crashing. But every time I click on the button, it shows me "Failed to query".

What's wrong here? Please HELP!!!


Solution

  • You are using SettingsActivity.checkBoxPreference means checkBoxPreference is currently a static field neither it points to any preference nor it knows it's behavior. It's using only declaration of fields.

    I usually do it by using following pattern

    SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this);
    

    Retrieve CheckBoxPreference using

    sharedPrefs.getBoolean("checkPref", false));
    

    I recommend you to generally follow this example.