Android - 带有单选按钮的Dialog中的空指针异常

时间:2012-04-20 16:35:59

标签: android

任何人都可以帮我解决这个问题并告诉我在哪里犯错误......当我尝试用radiobutton做任何事情时,Eclipse会抛出这个异常

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)
.
.
.

使用此代码

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);

1 个答案:

答案 0 :(得分:2)

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

应该是

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

注意对话框 .findViewById(R.id.DialogRb0);

当您在对话框的布局中搜索时,您正在主布局中搜索找到RadioButton对话框。当您搜索变量drb0时,它变为null,并且当您在其上调用setChecked(true)时将导致空指针异常。