0

I'm trying to return a function through JavascriptInterface but am getting an error:

Cannot refer to a non-final variable funct inside an inner class defined in a different method

here is the code:

         public void androidFieldPrompt(String title, String msg, 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();
                    webView.loadUrl("javascript:window."+funct+"('"+value+"')");
                    return;                  
                   }  
                 });   
            alert.setNegativeButton("CANCEL", null);
            alert.show();            
         }

1 Answer 1

1

The error says it all. The variable funct is not available in the scope of the anonymous event handler class:

That should do the trick:

 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();
                webView.loadUrl("javascript:window."+funct+"('"+value+"')");
                return;                  
               }  
             });   
        alert.setNegativeButton("CANCEL", null);
        alert.show();            
     }
Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting this error in production with final var: E/Web Console(26069): Uncaught TypeError: Property 'undefined' of object [object DOMWindow] is not a function at null:1
@ushdiver add a log output before loading the URL. Something like Log.d("ASDF", "My funct: " + funct); Maybe the value is null.
I was sending through the method instead of just the name of the method on the javascript side androidFieldPrompt('','Search the Help Database',promptResult); - changed to androidFieldPrompt('','Search the Help Database','promptResult'); . final did the trick after

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.