2

我试图通过在用户单击按钮时显示Toast来显示复选框状态,因为我正在使用 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)

(IE):

if (chkSubscribe.isChecked())
4

2 回答 2

4

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

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

你得到 NPE 因为你还没有初始化chkSubscribe

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

您还解雇了dialog在这种情况下chkSubscribe将为空的。

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

于 2013-07-12T06:57:39.650 回答
0

您在 click 内调用 findViewById,这里它不是在主活动类上调用 findViewByid,但 loginButton 和 loginButton 中没有复选框。您需要在 Activity 中调用此行“chkSubscribe = (CheckBox)findViewById(R.id.chkSubscribe);”,然后在 onClick 方法中引用它,记住您在 onClick 中调用此对象的任何方法都引用 loginButton 而不是您的活动

于 2013-07-12T06:55:05.297 回答