我有一个名为WebActivity的viewPager活动.viewPager使用webView片段的实例(片段里面包含一个webview)。我将viewAager的片段中的WebActivity的标题更改为“Loading ..”表示webView正在加载。它不会导致任何问题但是当我在页面中移动很多时我会遇到崩溃的日志,如下所示:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.setTitle(java.lang.CharSequence)' on a null object reference
at com.example.android.gametalks.Fragments.WebViewFragment$1.onPageFinished(WebViewFragment.java:91)
at com.android.webview.chromium.WebViewContentsClientAdapter.onPageFinished(WebViewContentsClientAdapter.java:199)
at org.chromium.android_webview.AwContentsClientCallbackHelper$MyHandler.handleMessage(AwContentsClientCallbackHelper.java:72)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
这是我的片段(相关部分):
public class WebViewFragment extends Fragment {
WebView mWebView;
String currentUrl;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
currentUrl = getArguments().getString("currentUrl");
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.webview_fragment, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Web View");
setRetainInstance(true);
mWebView = (WebView) view.findViewById(R.id.webvieww);
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
getActivity().setTitle("Loading...");
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
getActivity().setTitle("Web View");
}
});
if (savedInstanceState == null)
{
mWebView.loadUrl(currentUrl);
}
}
答案 0 :(得分:1)
简短回答:检查getActivity()
是否因为访问而返回null。
if(getActivity() != null) {
getActivity().setTitle("New title");
}
答案很长:最好使用某种监听器来通知活动片段内的更改,而不是直接使用getActivity()
。 Google Developer docs have a pretty good walkthrough如何使用界面实现此目的。