使用Checkbox的空指针异常

时间:2013-07-12 06:41:54

标签: android

我试图通过显示 Toast 来显示 Checkbox状态,只要用户在按钮上执行点击我正在使用AlertDialog,但获得空指针异常,

完成Logcat:

07-12 06:32:44.851: E/AndroidRuntime(783): FATAL EXCEPTION: main
07-12 06:32:44.851: E/AndroidRuntime(783): java.lang.NullPointerException
07-12 06:32:44.851: E/AndroidRuntime(783):  at com.example.UploadActivity$2.onClick(UploadActivity.java:271)
07-12 06:32:44.851: E/AndroidRuntime(783):  at android.view.View.performClick(View.java:4204)
07-12 06:32:44.851: E/AndroidRuntime(783):  at android.view.View$PerformClick.run(View.java:17355)
07-12 06:32:44.851: E/AndroidRuntime(783):  at android.os.Handler.handleCallback(Handler.java:725)
07-12 06:32:44.851: E/AndroidRuntime(783):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-12 06:32:44.851: E/AndroidRuntime(783):  at android.os.Looper.loop(Looper.java:137)
07-12 06:32:44.851: E/AndroidRuntime(783):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-12 06:32:44.851: E/AndroidRuntime(783):  at java.lang.reflect.Method.invokeNative(Native Method)
07-12 06:32:44.851: E/AndroidRuntime(783):  at java.lang.reflect.Method.invoke(Method.java:511)
07-12 06:32:44.851: E/AndroidRuntime(783):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-12 06:32:44.851: E/AndroidRuntime(783):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-12 06:32:44.851: E/AndroidRuntime(783):  at dalvik.system.NativeStart.main(Native Method)
07-12 06:32:50.332: E/Trace(1213): error opening trace file: No such file or directory (2)

loginbutton.setOnClickListener(new View.OnClickListener(){

                @Override
                    public void onClick(View v) {
                    SaveData();     
                    alertDialog.dismiss();

                    chkSubscribe = (CheckBox)findViewById(R.id.chkSubscribe);
                    if (chkSubscribe.isChecked())
                    {
                    Toast.makeText(UploadActivity.this,"You have Subscribed for Newsletter",
                    Toast.LENGTH_LONG).show();
                    }       
                    else {
                    Toast.makeText(UploadActivity.this,"You have Un-subscribed for Newsletter",
                    Toast.LENGTH_LONG).show();
                    }

                }

错误行:

com.example.UploadActivity$2.onClick(UploadActivity.java:271)

(即):

if (chkSubscribe.isChecked())

2 个答案:

答案 0 :(得分:4)

如果要为dialog充气布局,则需要使用对话框对象来初始化视图

      chkSubscribe = (CheckBox)dialog.findViewById(R.id.chkSubscribe);

您正在获取NPE因为您尚未初始化chkSubscribe

chkSubscribe = (CheckBox)findViewById(R.id.chkSubscribe) //初始化失败

您也在驳回dialogchkSubscribe将为空。

注意:您可以将当前视图层次结构的findViewById设置为活动。

答案 1 :(得分:0)

你在里面点击调用findViewById,这里没有调用主活动类的findViewByid,但是loginButton和loginButton没有复选框。你需要调用这行“chkSubscribe =(CheckBox)findViewById(R.id.chkSubscribe);”在Activity中然后在onClick方法中引用它,记住你在onClick上调用这个对象的任何方法请参考loginButton而不是你的活动< / p>