Search code examples
androidtogglebutton

If a toggle button is checked or not


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!


Solution

  • In your onCreate() method, you're calling checkNotify() before togglePref has been initialized. You want to move that initialization up (or move checkNotify() down.)