Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing an array of values from Android Activity to JavaScript in a WebView
    text
    copied!<p>I'm using a JS Charts library to draw graphs in a WebView of my Android Application. I want to provide the data from the SQLite database. At this moment I'm stuck on how to pass array of data from Java to JavaScript. The JavaScript part expects something like that:</p> <pre><code>data = new Array([10, 10], [20, 10]); </code></pre> <p>I know about the <code>addJavaScriptInterface</code> and I managed to pass single values from my Activity to a WebView. It's only the array that gives me trouble. I thought about something like that:</p> <pre><code>final class ChartDataLoader { public double[][] getData() { double[][] data = {{10, 10}, {20, 10}}; return data; } } </code></pre> <p>Note that for now I'm just hard-coding the data, but eventually this will be pulled out from a database. So then I expose this to my JS: </p> <pre><code>webView.addJavascriptInterface(new ChartDataLoader(), "dataLoader"); </code></pre> <p>And finally try to read it in JavaScript:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="jscharts.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="chartcontainer"&gt;You should see a chart here.&lt;/div&gt; &lt;script type="text/javascript"&gt; myData = dataLoader.getData(); alert("DataReceived: " + myData.length); alert("Element 0 : " + myData[0]); var myChart = new JSChart('chartcontainer', 'line'); myChart.setDataArray(myData); myChart.draw(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>JavaScript fails on those two alert statements stating:</p> <blockquote> <p>ERROR/Web Console(2455): Uncaught TypeError: Cannot read property 'length' of undefined at file:///android_asset/chart.html:15</p> </blockquote> <p>Any hints? I saw some code online where other people convert arrays to a String and then recreate it back in JavaScript but that seems like an overkill to me and I was hoping for a better solution. An alternative is to pass an XML file to the chart library, but again, I thought it would be slow to create a new XML every time a user wants to see a graph.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload