bushdiver bushdiver - 4 months ago 16
Android Question

android app crashing on webview url change

Similar to this question, but solutions are not working in mycase.

Android app is crashing when running function webview.loadUrl

Getting the following error on close:


E/AndroidRuntime(1593): Caused by:
java.lang.Throwable: Warning: A WebView method was called on thread
'WebViewCoreThread'. All WebView methods must be called on the UI
thread. Future versions of WebView may not support use on other
threads.


EDIT: Trying now to run the function in runOnUiThread(new Runnable(){ }) but getting errors and having trouble with where to enter runOnUiThread within context.

Here is full code:

public class MyJavaScriptInterface {
@JavascriptInterface
public void androidFieldPrompt(String title, String msg, final String funct) {
final EditText input = new EditText(MainActivity.this);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle(title);
alert.setMessage(msg);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();

// ERROR IS BEING THROWN HERE
webView.loadUrl("javascript:window."+funct+"('"+value+"')");

return;
}
});
alert.show();
}
}

Answer

E/AndroidRuntime(1593): Caused by: java.lang.Throwable: Warning: A WebView method was called on thread 'WebViewCoreThread'. All WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.

As the error points out .. you are calling webview methods on non UI Thread (inside a click listener ).

you should use runOnUiThread to use main thread when calling web view method , inside onClick

  MainActivity.this.runOnUiThread(new Runnable(){
       @Override
        public void run() {
           String value = input.getText().toString();
           webView.loadUrl("javascript:window."+funct+"('"+value+"')");
           return;
        }
 });