4

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:

data = new Array([10, 10], [20, 10]);

I know about the addJavaScriptInterface 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:

final class ChartDataLoader {

    public double[][] getData() {
        double[][] data = {{10, 10}, {20, 10}};
        return data;
    }
}

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:

webView.addJavascriptInterface(new ChartDataLoader(), "dataLoader");

And finally try to read it in JavaScript:

<html>
<head>
<script type="text/javascript" src="jscharts.js"></script>
</head>

<body>
<div id="chartcontainer">You should see a chart here.</div>

<script type="text/javascript">

 myData = dataLoader.getData(); 
 alert("DataReceived: " + myData.length);
 alert("Element 0 : " + myData[0]);

 var myChart = new JSChart('chartcontainer', 'line');
 myChart.setDataArray(myData);
 myChart.draw();

</script>
</body>
</html>

JavaScript fails on those two alert statements stating:

ERROR/Web Console(2455): Uncaught TypeError: Cannot read property 'length' of undefined at file:///android_asset/chart.html:15

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.

1
  • well, yes ... I think you will have to parse the string and recreate the array in JS. But, I do not see, why that would be such a problem? Commented Dec 2, 2010 at 2:27

2 Answers 2

5

Remove the line: alert("DataReceived: " + myData.length);

Sign up to request clarification or add additional context in comments.

Comments

0

To fix the most recent error you need to define myData as a var.

What you talk about at the end of your question (converting arrays to string) is JSON. Any context switch is expensive (e.g. Android to web). The serialisation/de-serialisation probably won't slow you down too much.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.