任何时候我按Back键,我的应用程序崩溃了。我试过不同的方式,他们都崩溃抛出NullPointerException ....任何想法?
方式1:
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the BACK key and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the BACK key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
方式2:
public void onBackPressed() {
myWebView.goBack();
return;
}
堆栈追踪:
11-19 20:13:12.425: E/AndroidRuntime(1963): FATAL EXCEPTION: main
11-19 20:13:12.425: E/AndroidRuntime(1963): java.lang.NullPointerException
11-19 20:13:12.425: E/AndroidRuntime(1963): at com.meanwhileinwv.android.MNWVShow.onBackPressed(MNWVShow.java:27)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.app.Activity.onKeyUp(Activity.java:1983)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.view.KeyEvent.dispatch(KeyEvent.java:1518)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.app.Activity.dispatchKeyEvent(Activity.java:2163)
11-19 20:13:12.425: E/AndroidRuntime(1963): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1747)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2702)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2677)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.view.ViewRoot.handleMessage(ViewRoot.java:1965)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.os.Looper.loop(Looper.java:143)
11-19 20:13:12.425: E/AndroidRuntime(1963): at android.app.ActivityThread.main(ActivityThread.java:4263)
11-19 20:13:12.425: E/AndroidRuntime(1963): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 20:13:12.425: E/AndroidRuntime(1963): at java.lang.reflect.Method.invoke(Method.java:507)
11-19 20:13:12.425: E/AndroidRuntime(1963): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-19 20:13:12.425: E/AndroidRuntime(1963): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-19 20:13:12.425: E/AndroidRuntime(1963): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
在调用myWebView
时,从共享代码中获取堆栈跟踪的唯一方法是null
为myWebView.goBack()
。要向您自己证明这一点,请修改您的onBackPressed()
:
public void onBackPressed() {
if (myWebView != null) {
myWebView.goBack();
}
}
异常应该消失。 (虽然,显然,你仍然不会发生任何后退行为。)
可能的原因:
myWebView
不是您班级中的成员变量。您可能已在另一个方法中声明并设置它,这意味着它不在onBackPressed的范围内。myWebView
不是引用WebView的变量的实际名称myWebView
曾用于引用您的WebView但在某些时候再次设置为null
myWebView
指向WebView
的代码实际设置为null
。例如,由于您指定了错误的ID,实际上未找到findViewById
的{{1}}来电将返回WebView
。如果您仍然卡住,请将代码发布到声明null
的位置以及分配位置。
答案 1 :(得分:1)
该代码中唯一的共同点是myWebView。你确定它不是空的吗?