每次用户从选项菜单中选择“logout”(R.Id.logout)时,我都会收到空指针异常。我无法弄清楚我没有初始化。
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.settings:
return false;
case R.id.about:
this.startActivity(new Intent(this, About.class));
return true;
case R.id.logout:
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setTitle("Logout");
alertbox.setMessage("Logging out will remove your credentials from this phone. \nDo you want to logout?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Editor e = loginPref.edit();
e.clear();
Homepage.this.startActivity(new Intent(getApplicationContext(), Login.class));
Homepage.this.finish();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = alertbox.show();
return true;
}
return false;
}
logcat的
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): FATAL EXCEPTION: main
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): java.lang.NullPointerException
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at org.*****.android.Homepage$1.onClick(Homepage.java:79)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at android.os.Handler.dispatchMessage(Handler.java:99)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at android.os.Looper.loop(Looper.java:123)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at java.lang.reflect.Method.invokeNative(Native Method)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at java.lang.reflect.Method.invoke(Method.java:521)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-16 10:09:49.705: ERROR/AndroidRuntime(1531): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
这很简单。 Homepage.java中第79行的内容为null。请检查这是什么行,并发布或发布完整的代码,包名称和一切,以便我们实际上可以提供帮助,因为现在我们只能猜测实际上是什么。
我的第一个猜测是loginPref at:
Editor e = loginPref.edit();
您是否已初始化loginPref?