我正在创建一个应用程序,我正在使用对话框接受,存储和显示数据,它可以找到我,但每当我重新启动我的应用程序,获得 NPE
@Override
public void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_LOGIN:
final AlertDialog alertDialog = (AlertDialog) dialog;
.........
.........
// check for parent email
if(GetEventsActivity.parental.equals("no")) // throwing error
{
// hide
parental_email.setVisibility(View.GONE);
}
else
{
// show
parental_email.setVisibility(View.VISIBLE);
}
........
}
}
我在列表项中显示按钮,每当用户点击该按钮时,我都会显示对话框。
btnData.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
showDialog(DIALOG_LOGIN);
}
});
和日志说:
W/dalvikvm(26689): threadid=1: thread exiting with uncaught exception (group=0x41a4d2a0)
E/AndroidRuntime(26689): FATAL EXCEPTION: main
E/AndroidRuntime(26689): java.lang.NullPointerException
E/AndroidRuntime(26689): at app.mac.Camera.UploadActivity.onPrepareDialog(UploadActivity.java:469)
E/AndroidRuntime(26689): at android.app.Activity.onPrepareDialog(Activity.java:3071)
E/AndroidRuntime(26689): at android.app.Activity.showDialog(Activity.java:3134)
E/AndroidRuntime(26689): at android.app.Activity.showDialog(Activity.java:3085)
E/AndroidRuntime(26689): at app.mac.Camera.UploadActivity$ImageAdapter$2.onClick(UploadActivity.java:286)
E/AndroidRuntime(26689): at android.view.View.performClick(View.java:4223)
E/AndroidRuntime(26689): at android.view.View$PerformClick.run(View.java:17275)
E/AndroidRuntime(26689): at android.os.Handler.handleCallback(Handler.java:615)
E/AndroidRuntime(26689): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(26689): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(26689): at android.app.ActivityThread.main(ActivityThread.java:4921)
E/AndroidRuntime(26689): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(26689): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(26689): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)
E/AndroidRuntime(26689): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)
E/AndroidRuntime(26689): at dalvik.system.NativeStart.main(Native Method)
I/Process(26689): Sending signal. PID: 26689 SIG: 9
答案 0 :(得分:4)
确实意味着
GetEventsActivity.parental
是null
。另一方面,我建议总是将常量字符串与可以改变的字符串进行比较
if ("no".equals(GetEventsActivity.parental))
这样你至少可以避免NPE
,因为第一次测试将是
if (! (GetEventsActivity.parental instanceof String))
return false;
且null instanceof String
始终为false