Understanding and Fixing BadTokenException in Android WebView

The Problem

So you have successfully created a webView in your App and already loaded your URL into it.

1
2
3
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.loadUrl(url);

However, any interaction with the page (such as a dropdown menu) will result in BadTokenException crash with the following error message:

FATAL EXCEPTION: main  
android.view.WindowManager$BadTokenException: Unable to add window — token is not valid; is your activity running?

The Cause

This happens when app wants to open a new dialog (e.g. for dropdown menu aka. spinner) while the container activity no longer exists.

The Solution

Create your WebView using the Activity Context rather than application context. Or if this is a child activity use parent activity context instead.

1
2
3
4
5
FrameLayout webViewContainer = (FrameLayout) findViewById(R.id.webViewContainer);
webView = new WebView(getParent());
webViewContainer.addView(webview);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url);