Question

I'm working on an Android app "native written in java" and I'm getting a response from a server the response is a javascript function

I need to use this function to do some calculations inside my native java code.

any ideas how to do so.

sample response :

function logic_1(surveyString, responseValuesString) { 
    var survey = eval(surveyString);
    var responseValues = eval(responseValuesString);
    var target = new Object();
if (isChosen(128133225, responseValues)) { 
target.id = 2;
}
if (! target.id) { 
    target.id = 2;
 } 
    return target;
 } 
Was it helpful?

Solution

I've previously used Rhino successfully to execute JavaScript code on Android: http://www.mozilla.org/rhino/

OTHER TIPS

Here's an example of how to return values from a complex type:

String strFunction = 
        "function add(x,y){ " +
            "return { " +
                "id:x+y " +
            "}; " +
        "}";

Context context = Context.enter();
ScriptableObject scope = context.initStandardObjects();
context.evaluateString(scope, strFunction, "test", 1, null);

Function functionAdd = (Function)scope.get("add");
NativeObject untypedResult = (NativeObject)functionAdd.call(context, scope, scope, new Object[] { 1, 2 });
double id = (Double)untypedResult.get("id", untypedResult);

The important part is the last two lines, where we call the JavaScript function, treat the result as a NativeObject, and then retrieve the value of the 'id' property from that object.

Maybe you just need to use a JavaScript auto executing function like this:

(function(x, y){
  var result;
  result = x + y; // do some calculations
  return result;
})(1 , 2); //  you can set your parameters from Java

and 1, 2 are just two parameters from Java

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top