Search code examples
javascriptjavaandroidandroid-libraryrhino

How to get values from a Java HashMap in javascript function using Rhino


I am using Rhino library to execute JavaScript functions in android. I have a javascript function like,

var exucuteJS = function(controlValues) {
var valueSelected = controlValues['country'];
valueSelected = valueSelected.toUpperCase();
 switch (valueSelected) {
    case "INDIA":
        return "IND_HOME";
    case "NEPAL":
        return "NEP_HOME";
    default:
        return "DEF_HOME"
 }
}

I am passing a Java HashMap object as parameter, say controlValues to the function executeJS. The problem is , the Rhino cant javascript code, to get the value from the key.

var valueSelected = controlValues['country'];

the return value is undefined.

it works fine with this line,

var valueSelected = controlValues.get('country');

but its not valid javascript code.

The same javascript is to be executed both in android and iOS. the above line will not supported in iOS. Please suggest. I am using latest version of Rhino.


Solution

  • Finally Myself found the answer.

    Rather than sending a HashMap to the javascript function, need to send it as a JSONObject. Not like a normal JSONObject's object but as a Object which is in the form of NativeJSON object.

    Object nativeJsonObject= NativeJSON.parse(rhino,scope,controlValueJsonString,new NullCallable());
    

    where, rhino - Rhino's Context object. scope - Scriptable's object controlValueJsonString - JSON string equivalent to the HashMap. (controlValueJsonString = new Gson().toJson(hashMap);)

    NullCallable is a class implemented from Callable,(package from rhino's org.mozilla.javascript.Callable)

    this 'nativeJsonObject' should be passed to javascript function.

    Object[] params = new Object[] { controlValues };
    

    from a JSON object, javascript can get the values as,

    var valueSelected = controlValues['country'];
    

    this is working for me. Really i dont know why down voted to this question. Admins, please note this issue.