Passing an array from Activity to Javascript

I know that there are several threads similar to this, but they do not answer the above question. Question Firts: Is it true that only primitives can be passed? (String, boolean, ...) Second question: if so. I have a String array in my activity and I need it to populate the html table in my WebView and apparently I need to use the Javascript interface to do this. So the question is: how can I do this? Do I need to create a string in my activity, pass it to JS and restore the array?

+4
source share
2 answers

You can use JSON as a format for your data. An easy way would be to use lib like GSON http://code.google.com/p/google-gson/ , which will make it easier to convert your ArrayList with native object types to strings.

Send this to your WebView via the Javascript interface and use JSON.parse (Stringname) in JS to recreate your array.

Regards Tim

+2
source

Your option is to expose the method using strings, and then you can use 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"}'

+1
source

Source: https://habr.com/ru/post/1381322/


All Articles