Search code examples
javascriptjavalistparameter-passingwikitude

Passing a list of string as an argument to javascript function from native java code


I have a javascript function:

drawPath: function drawPathFn(nodeList){
        console.log(""+nodeList[1]);
},

and the native java code that calls this function is:

List<String> nodes = getShortestPath(s, d);
architectView.callJavascript("World.drawPath('"+nodes+"')");

nodes list is filled with several location names but when I try to pass this list to the javascript function, the console output is just: "[" for console.log(""+nodeList[0]); and "S" for console.log(""+nodeList[1]);

What I want is that when I call nodeList[0], I want it to print out e.g. "Building A". How could I achieve that?


Solution

  • You'll need to pass a JSObject or a String as a literal array in javascript, i.e. "['str0','str1']". Here's how to use a JSObject:

    //first we need an Iterator to iterate through the list
    java.util.Iterator it = nodes.getIterator();
    //we'll need the 'window' object to eval a js array, you may change this
    //I dont know if you are using an applet or a javaFX app. 
    netscape.javascript.JSObject jsArray = netscape.javascript.JSObject.getWindow(YourAppletInstance).eval("new Array()");
    //now populate the array 
    int index = 0;
    while(it.hasNext()){
      jsArray.setSlot(index, (String)it.next());
      index++;
    }
    //finaly call your function
    netscape.javascript.JSObject.getWindow(YourAppletInstance).call("World.drawPath",new Object[]{jsArray});
    

    Here's how to do it with a literal String:

    java.util.Iterator it = nodes.getIterator();
    int index = 0;
    String literalJsArr = "[";
    //populate the string with 'elem' and put a comma (,) after every element except the last 
    while(it.hasNext()){
      literalJsArr += "'"+(String)it.next()+"'";
      if(it.hasNext() ) literalJsArr += ",";
      index++;
    }
    literalJsArr += "]"; 
    architectView.callJavascript("World.drawPath("+literalJsArr+")");
    

    reference:

    http://www.oracle.com/webfolder/technetwork/java/plugin2/liveconnect/jsobject-javadoc/netscape/javascript/JSObject.html https://docs.oracle.com/javase/tutorial/deployment/applet/invokingJavaScriptFromApplet.html