3

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?

user997248
  • 73
  • 2
  • 10
  • I'm not familiar with Java, but it looks very strange to me that you can concatenate a List onto a String without getting a compile error. That aside, it looks to me that what you are passing to `drawPathFn` is the toString'd result of your Java `nodes`. – 76484 Oct 18 '15 at 09:33
  • Yes your are right but I am not using toString function or anything. Even I send only one item in the list like nodes.get(0) it still behaves same. – user997248 Oct 18 '15 at 09:46
  • If you want JavaScript to treat your item as an array, then it must be structured like an array. `"World.drawPath([" + String.join(", ", nodes) + "]);"); – 76484 Oct 18 '15 at 09:52
  • Oops. Because it should be an array of strings, we will need to include the quotes for each string in our array: `"World.drawPath(['" + String.join("', '", nodes) + "']);");` – 76484 Oct 18 '15 at 10:08

1 Answers1

0

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