user3188481
user3188481

Reputation: 45

how can i get on click to check what check box is checked and if button is pressed

I am trying to get my on click method to listen for submit button and check what check box is checked to load a certain activity based on that check box here is what code i have for this function but it keeps crashing my android app. Can somebody please indicate what i may be doing wrong . please ignore any spelling or grammer mistakes as i have dilexsia.

if (v.getId() == R.id.submit) {
    Intent intent = new Intent(ModeSelect.this, OnePSetup.class);         
    if (checkBox.isChecked()){
        startActivity(intent);
        System.out.println("checked");
    }
}

This is the outpu error

    11-14 15:36:09.820  12457-12478/allanwalls1304988.straight4 E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xb4057be0

11-14 15:36:11.952 12457-12457/allanwalls1304988.straight4 E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: allanwalls1304988.straight4, PID: 12457 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference at allanwalls1304988.straight4.ModeSelect.onClick(ModeSelect.java:58) at android.view.View.performClick(View.java:5198) at android.view.View$PerformClick.run(View.java:21147) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Upvotes: 2

Views: 109

Answers (2)

harshitpthk
harshitpthk

Reputation: 4136

Your checkbox is referenced with a local variable inside onCreate() method make it field reference. It shouldn't give null pointer then. Declare it as a field

private CheckBox checkBox;

inside onCreate() method

checkBox = (CheckBox) findViewById(R.id.cb1); 

Upvotes: 1

Huzaima Khan
Huzaima Khan

Reputation: 63

From stack trace you posted, the error is at ModeSelect.java line number 58 and the error is on the execution of this line checkBox.isChecked(). It seems that you haven't initilized checkBox which causes it to throw NullPointerException. You can initilized it like this:

CheckBox checkBox = (CheckBox) findViewById(R.id.myCheckBox);

Hope this helps.

Upvotes: 1

Related Questions