Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 946
Ryan Ciehanski Avatar asked Jun 02 '11 23:06

Ryan Ciehanski


2 Answers

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()) {
like image 164
WarrenFaith Avatar answered Oct 23 '22 19:10

WarrenFaith


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

like image 35
Dan Breslau Avatar answered Oct 23 '22 17:10

Dan Breslau