Java nullpointer exception from Webview in android

2019-05-06 14:35发布

问题:

Following the suggestions provided in this question I modified my AdMob code to be compliant with the recommendations, that effectively worked reducing the number of exceptions that were appearing. However a new exception is rising.

The code is the following:

@Override
protected void onDestroy() {
    if ( adView != null ) {
          adView.destroy();
          adView = null;

          Log.i(ApplicationData.APP_TAG, TAG + ": OnDestroy, destroying the Adview");
     }

    super.onDestroy();
}

The method adView.destroy() appears to work well as the LogCat message is published. Just after this message I am getting the following exception on WebView:

java.lang.NullPointerException
    at android.webkit.WebViewClassic.loadDataWithBaseURL(WebViewClassic.java:2741)
    at android.webkit.WebView.loadDataWithBaseURL(WebView.java:919)
    at com.google.android.gms.ads.internal.request.n.run(SourceFile:206)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:153)
    at android.app.ActivityThread.main(ActivityThread.java:5297)
    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:833)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
    at dalvik.system.NativeStart.main(Native Method)

Unfourtunately I am not able to find a way to reproduce the problem but is happening in production regularly. I have not been able to find any problem, has somebody any hint of what I can do?

回答1:

One of Google Mobile Ads SDK Team said (March 14),

We looked into this issue when it was first reported, and a fix has been released within Google Play services. You should see fewer and fewer instances as your users' devices update to the new version.

Refer to https://groups.google.com/forum/#!topic/google-admob-ads-sdk/oYpQI_L14Tg



回答2:

This occurs when the WebView is destroyed before loadDataWithBaseUrl is called( probably by other thread). In AdMob code, i saw that they handle this now as follows

public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) {
        synchronized(this) {
            if(!this.isDestroyed()) {
                super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
            } else {
                Log.d("The webview is destroyed. Ignoring action.");
            }

        }
    }

So it should not occur now.