Ynnad Ynnad - 4 months ago 16
JSON Question

Inject JSONArray to webiew via addJavascriptInterface

I have an html page stored locally on my Android app assets. I want to display it within a WebView and to add some parameters to the web page.

I put all my values into a JSONArray and then I use 'addJavascriptInterface' to add this JSONArray to the webpage javascript.

But when I try to use the value in javascript, it's of type [object Object] and with a length undefined...

JSONArray json = buildJSONArray();

webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);

webView.addJavascriptInterface(json, "data");
webView.loadUrl("file:///android_asset/test.html");


I trie to replace the jsonArray by a simple String, and the same thing happen...

How can I send a javascript parameter to my html page from Android ?' Apparently I've miss something with the 'addJavascriptInterface' method...

Thanks :)

Answer

Android: return Json as string

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "gokul");
json=jsonObject.toString();
return json;

javascript: parse the json string

var json=JSON.parse(json);