A solution in Android where webView calls JS incorrectly

  • 2020-06-15 10:10:09
  • OfStack

The problem

There was an error with webView calling JS.


    class TestJS {
        ......
        public TestJS(){
        }
       
        public void save(String data){           
            webView.loadUrl("javascript: alert(" + data +")");
        }
        ......
    }


    W/WebView(2088): 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) {b3dbcb18} called on Looper (JavaBridge, tid 120) {b44a1af8}, FYI main Looper is Looper (main, tid 1) {b3dbcb18})
    W/WebView(2088):     at android.webkit.WebView.checkThread(WebView.java:2063)
    W/WebView(2088):     at android.webkit.WebView.loadUrl(WebView.java:794)
    W/WebView(2088):     at com.ue.oa.activity.XFormActivity.alert(XFormActivity.java:180)
    W/WebView(2088):     at com.ue.oa.activity.XFormActivity$FormActions.save(XFormActivity.java:193)
    W/WebView(2088):     at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
    W/WebView(2088):     at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
    W/WebView(2088):     at android.os.Handler.dispatchMessage(Handler.java:102)
    W/WebView(2088):     at android.os.Looper.loop(Looper.java:136)
    W/WebView(2088):     at android.os.HandlerThread.run(HandlerThread.java:61)

To solve

The save method is modified to:


    public void save(String data){           
        webView.post(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript: alert(" + data +")");
            }
        });
    }

That's the solution, isn't it easy? I hope you like it.


Related articles: