Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  71] [ 5]  / answers: 1 / hits: 33120  / 11 Years ago, fri, january 10, 2014, 12:00:00

I have the following java code in my Android application and wanted a way to convert the Java list to an array that can be used in javascript:



Java:



public void onCompleted(List<GraphUser> users, Response response) {
for(int i = 0; i < users.size(); i++)
{
//add to an array object that can be used in Javascript
webView.loadUrl(javascript:fetchFriends(arrObj));
}
}


Javascript:



  //this is how I want to be able to use the object in Javascript
function parseFriends(usersObjectFromJava){
var users = [];
for (var i = 0; i < usersObjectFromJava.length; i++) {
var u = {
Id: usersObjectFromJava[i].id + ,
UserName: usersObjectFromJava[i].username,
FirstName: usersObjectFromJava[i].first_name,
LastName: usersObjectFromJava[i].last_name,
};
users[i] = u;
}
}


Could some help me with the Java code to create the usersObjectFromJava so that it can be used in javascript?


More From » java

 Answers
3

I would assume doing this:



Java:



public void onCompleted(List<GraphUser> users, Response response) {
JSONArray arr = new JSONArray();
JSONObject tmp;
try {
for(int i = 0; i < users.size(); i++) {
tmp = new JSONObject();
tmp.put(Id,users.get(i).id); //some public getters inside GraphUser?
tmp.put(Username,users.get(i).username);
tmp.put(FirstName,users.get(i).first_name);
tmp.put(LastName,users.get(i).last_name);
arr.add(tmp);
}

webView.loadUrl(javascript:fetchFriends(+arr.toString()+));
} catch(JSONException e){
//error handling
}
}


JavaScript:



function fetchFriends(usersObjectFromJava){
var users = usersObjectFromJava;
}


You will have to change the Java-Code a bit (i.e. using public getters or add more/less information to the JSONObjects.
JSON is included in Android by default, so no external libraries are necessary.



I hope i understood your problem.



Small thing i came across: you where using fetchFriends in Java but its called parseFriends in Javascript, I renamed them to fetchFriends


[#73259] Thursday, January 9, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamaal

Total Points: 515
Total Questions: 102
Total Answers: 107

Location: France
Member since Thu, May 6, 2021
3 Years ago
;