3

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);

       }
});
2
  • Fixed the above issue by this "common.ContinueInspectionOffline('"+sub_url_vin+"')". Will help anyone future Commented Mar 25, 2021 at 12:06
  • Can you add that in answer. I did not understand. Commented Oct 24, 2021 at 0:18

1 Answer 1

2

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);
    
     
Sign up to request clarification or add additional context in comments.

Comments

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.