Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();        
             }
   }
like image 555
bushdiver Avatar asked Feb 14 '23 21:02

bushdiver


2 Answers

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;
        }
 });
like image 53
Shubhank Avatar answered Feb 27 '23 15:02

Shubhank


Alternatively, you can use Runnable in order to use WebView on UI thread and eliminate the issue:

webView.post(new Runnable()
{
    @Override
    public void run()
    {
       String value = input.getText().toString();
       webView.loadUrl("javascript:window."+funct+"('"+value+"')");
    }
});
like image 28
Ayaz Alifov Avatar answered Feb 27 '23 13:02

Ayaz Alifov