nasdaq
nasdaq

Reputation: 25

Android - NullPointer exception in Dialog with RadioButtons

Can anyone help me with this and tell me where I do the mistake... When I try to do anything with the radiobutton Eclipse throws me this exception

threadid=1: thread exiting with uncaught exception (group=0x40015560)
FATAL EXCEPTION: main
java.lang.NullPointerException
cz.nasdaq.RbtnActivity$1.onClick(RbtnActivity.java:36)
android.view.View.performClick(View.java:2485)
android.view.View$PerformClick.run(View.java:9080)
android.os.Handler.handleCallback(Handler.java:587)
android.os.Handler.dispatchMessage(Handler.java:92)
android.os.Looper.loop(Looper.java:123)
.
.
.

with this code

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn = (Button)findViewById(R.id.btn1);        
        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                final Dialog dialog = new Dialog(RbtnActivity.this);
                dialog.setContentView(R.layout.dlg);
                dialog.show();

                RadioButton drb0=(RadioButton)findViewById(R.id.DialogRb0);
                drb0.setChecked(true);

Upvotes: 0

Views: 340

Answers (1)

dymmeh
dymmeh

Reputation: 22306

RadioButton drb0=(RadioButton)findViewById(R.id.DialogRb0);
drb0.setChecked(true);

should be

RadioButton drb0=(RadioButton)dialog.findViewById(R.id.DialogRb0);
drb0.setChecked(true);

Note the dialog.findViewById(R.id.DialogRb0);

You are searching in your main layout to find the dialog RadioButton when you should be searching within the dialog's layout. Your variable drb0 is null when you search for it and will cause the null pointer exception when you call setChecked(true) on it.

Upvotes: 2

Related Questions