Mark
Mark

Reputation: 156

Webview crash after fragment tab change

I have a activity with 3 actionbar tabs. Each tab contains a webview which loads a URL at Fragment oncreate(). Everything is working fine but if i switch tabs quickly the onpagefinished appears after the tab change so when the calling fragment is gone, resulting in an NullPointerException. Is there a way to prevent this?

I tried in my fragment:

public void onDestroy() {
        super.onDestroy();
        try {
            myWebView.stopLoading();
        } catch (Exception e) {
        }
        try {
            myWebView.clearView();
        } catch (Exception e) {
        }

and in my tab listener:

onTabSelected(Tab tab, FragmentTransaction ft) {
        // StartActivity.mViewPager.setCurrentItem(tab.getPosition());
        if (FinishedLoading == true){
        ft.replace(R.id.fragment_container, fragment);
        }
        }

Both options don't prevent the APP to crash.

The error i recieve:

java.lang.NullPointerException
at com.***.Fragment1$MyWebViewClient.onPageFinished(Fragment1.java:233)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:389)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)

Upvotes: 1

Views: 631

Answers (1)

SilverHood
SilverHood

Reputation: 723

I was facing this issue as well. If you haven't solved it, maybe you would like to try implementing onPause in your fragment like this:

@Override
public void onPause() {

    if (webview.isShown() == false) {
        webview.stopLoading();
    }
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
}

Where webview is your webview

Upvotes: 1

Related Questions