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!!!
You are using
SettingsActivity.checkBoxPreferencemeanscheckBoxPreferenceis currently astaticfield neither it points to anypreferencenor it knows it's behavior. It's using only declaration of fields.I usually do it by using following pattern
Retrieve
CheckBoxPreferenceusingI recommend you to generally follow this example.