If a toggle button is checked or not

Ryan Ciehanski picture Ryan Ciehanski · Jun 3, 2011 · Viewed 29.3k times · Source

Well I am trying to see if a checkbox is checked or not, but I get errors.

Defining the checkbox code:

public class Preferences extends PreferenceActivity {

CheckBoxPreference togglePref;

...
}

CheckBox Code:

public void checkNotify() {   

if (togglePref.isChecked()==(true)) {

...

   }

}

OnCreate code:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //SharedPreferences settings = getSharedPreferences("EasySettingsPreferences", MODE_PRIVATE);
    //boolean notify = settings.getBoolean("notify", false);

    checkNotify();
    rootView = new LinearLayout(this);
    rootView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    rootView.setOrientation(LinearLayout.VERTICAL);

    togglePref =  new CheckBoxPreference(this);

    textView = new TextView(this);
    textView.setText(R.string.app_name);

    titleView = new LinearLayout(this);
    titleView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 26));
    titleView.setBackgroundResource(R.drawable.pattern_carbon_fiber_dark);

    titleView.addView(textView);
    preferenceView = new ListView(this);
    preferenceView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    preferenceView.setId(android.R.id.list);
    PreferenceScreen screen = createPreferenceHierarchy();
    screen.bind(preferenceView);
    preferenceView.setAdapter(screen.getRootAdapter());

    rootView.addView(titleView);
    rootView.addView(preferenceView);

    this.setContentView(rootView);
    setPreferenceScreen(screen);

}

Logcat Picture:

logcat pic http://img710.imageshack.us/img710/8529/unledxq.png

Debugger Picture

debugger pic http://img847.imageshack.us/img847/1192/unled1rn.png

Please help me if you can. Thanks!

Answer

WarrenFaith picture WarrenFaith · Jun 3, 2011

I guess that you never initialise togglePref. To be sure we need to see the onCreate(). (I will update my answer if my guess was wrong...)

edit I was right. You call checkNotify() before your even initialized the togglePref variable. Check your logic if it really makes sense to call that method before everything else or if it is fine if you call it later.

A tip: You can simplify your if statement:

// yours:
if (togglePref.isChecked()==(true)) {
// simplified:
if (togglePref.isChecked()) {