I am getting a null pointer exception every time the user selects "logout" (R.Id.logout) from the option menu. I can't figure out what I'm not initialising.
@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
0开发者_如何学运维8-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)
It's quite simple. Something on line 79 in Homepage.java is null. Please check what line this is and post it or post the complete code, with package name and everything so that we actually can help because now we can only guess what's actually null.
My first guess would be loginPref at:
Editor e = loginPref.edit();
Have you initialized loginPref?
精彩评论