Javascript – Reloads the WebView using JavaScript calls from the loaded web page

Reloads the WebView using JavaScript calls from the loaded web page… here is a solution to the problem.

Reloads the WebView using JavaScript calls from the loaded web page

I have a WebView in an application that loads a specific web page.

There is a button on the web page that uses JavaScript to call a method in the Android activity to reload the URL in the WebView (effectively resetting the web app to its default state).

Since there are several threads here, I’ve got all of Android’s JavaScript interfaces working, and I can pop up a toast to show that the app is about to reload, but I get an error with my WebView.loadUrl() call as shown below.

java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {1d015c84} called on Looper (JavaBridge, tid 122148) {33703881}, FYI main Looper is Looper (main, tid 1) {1d015c84})

I’m guessing this is because the method that does the reload isn’t in the activity’s onCreate method, which does all the other WebView operations, but I’m not sure if that’s really the problem, and if so, how to fix it – because the method for reloading URLs needs to be in the JavascripInterface class to be accessible from within the web page.

Solution

For some reason, loading a page (or reloading) in a WebView component needs to be done on the UI thread, so simply wrapping the reload call in a runOnUiThread fixes this issue.

    @JavascriptInterface
    public void reloadSite(){
        Toast.makeText(mContext, getString(R.string.reloadingWebApp), Toast.LENGTH_LONG).show();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView = (WebView) findViewById(R.id.activity_main_webview);
                mWebView.loadUrl(getString(R.string.web_app_url));
            }
        });
    }

Related Problems and Solutions