2

I tried to pass a string parameter to the web app javascript code. It's failed while passing a variable with the string value. But it works when we hardcode the data. Please let me know what's wrong with this.

Working hardcoded code:

mWebview.evaluateJavascript("cm.setData('N051783')", new ValueCallback<String>() {

     @Override
     public void onReceiveValue(String value3) {

          Log.d(" setData Return Value"," setData Return... "+value3);

     }
});

Not working code with string variable

mWebview.evaluateJavascript("cm.setData("+sub_data+")", new ValueCallback<String>() {

       @Override
       public void onReceiveValue(String value3) {

            Log.d(" sub_data Return Value"," sub_data Return... "+value3);

       }
});
Rohit Singh
  • 16,950
  • 7
  • 90
  • 88
Malhotra
  • 221
  • 3
  • 13

1 Answers1

1

You are probably missing ""

My JavaScript function at com.UserProfile

function setUserName(name){
   alert('username is ' + name)
}

How to call it from Java

mWebview.evaluateJavascript("com.UserProfile.setUserName("Rohit")",null);

How to pass the parameter?

You need to concatenate " with parameter. " is a special character. This is how you can concatenate " in a String.

Here is an example:

String username = "Rohit";
String func = com.UserProfile.setUserName(\""+ username + "\")";

mWebview.evaluateJavascript(func, null);

You can use StringBuilder to concatenate as well as"

Let's break it down line by line;

StringBuilder sb = new StringBuilder();
sb.append("com.UserProfile.setUserName")   //com.UserProfile.setUserName
  .append("(")                             //com.UserProfile.setUserName(
  .append("\"")                            //com.UserProfile.setUserName("
  .append(username)                        //com.UserProfile.setUserName("Rohit
  .append("\"")                            //com.UserProfile.setUserName("Rohit"
  .append(")")                             //com.UserProfile.setUserName("Rohit")

 String func = sb.toString();

 mWebview.evaluateJavascript(func, null);
    
     
Rohit Singh
  • 16,950
  • 7
  • 90
  • 88