Daniele Anzelmi
Daniele Anzelmi

Reputation: 97

Passing Array from Activity to Javascript

I know there a couple of threads similar to this one but they dont actually answer the above question. Firts question: is it true that only primitives can be passed? (String, boolean,...) Second question: if it is so. I have an array of String in my activiy and i need it to fill a html table in my WebView and apparently i need to use Javascript interface to do so. So the question is: How can i do that? Do I need to create a string in my activity, pass it to JS and once there recreate the array?

Upvotes: 4

Views: 2139

Answers (3)

Ray
Ray

Reputation: 11

"Do I need to create a string in my activity, pass it to JS and once there recreate the array?" That's the way i resolved it in my case ; i appended a special character to each item in the list while building up the string and later split it up in JS.

var strings = get.list(); // long string from activity.
var item1 = strings.split("=")[0];
var item2 = strings.split("=")[1];

.... Or you could go for a library

Upvotes: 1

SergioM
SergioM

Reputation: 1605

Your option is to expose the method using strings and then you can use the JSONObject or JSONArray to parse the string and use it accordingly.

Here is what I did.

@JavascriptInterface
public void passJSON(String array, String jsonObj) throws JSONException
{
    JSONArray myArray = new JSONArray(array);
    JSONObject myObj = new JSONObject(jsonObj);     
    ...

}

where array is '["string1","string2"]' and jsonObj is '{attr:1, attr2:"myName"}'

Upvotes: 1

Tim
Tim

Reputation: 6712

You could use JSON as format for your data. A simple way would be to use a lib like GSON http://code.google.com/p/google-gson/ which makes it easy to convert your ArrayList with own object-types to Strings.

Send that to your WebView via the Javascript-interface and use JSON.parse(Stringname) in JS to recreate your Array.

Best wishes, Tim

Upvotes: 2

Related Questions