1

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;
 } 
Helal Ismail
  • 518
  • 1
  • 10
  • 22

3 Answers3

3

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

Ian Newson
  • 7,679
  • 2
  • 47
  • 80
  • I'm getting response as a function that takes 2 input parameters .. can I give this function input from my java code ? I mean "function logic_1(surveyString, responseValuesString)" any way to set those 2 parameters from Java ?? – Helal Ismail Mar 28 '12 at 09:32
  • Yes, this is not a problem with the Rhino APIs. This answer describes how to do it: http://stackoverflow.com/a/3996115/511012 – Ian Newson Mar 28 '12 at 10:00
  • works perfect ! thanks okay just another question ... you can see that the function is returning an object var target = new Object(); I was able to catch an integer, boolean, string in the return but how to catch an object ? – Helal Ismail Mar 28 '12 at 12:59
  • I've posted an example as a separate answer, so I could include code. – Ian Newson Mar 28 '12 at 13:45
1

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.

Ian Newson
  • 7,679
  • 2
  • 47
  • 80
0

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

antonjs
  • 14,060
  • 14
  • 65
  • 91