I wanted to visualize data using graphs in one of the Android app that I was developing and found that Android SDK don’t provide a good graphing API, which you can use out of the box.
You have to either using Canvas 2D graphics to draw your graphs from scratch or use some commercial components.
If you can assume that some form of Internet connection will be available then you can use Google Graphs API to get the graph and embed it in a webview control. But I didn’t wanted to make that assumption and so I started to search for a good graph component, which I can use in my app.
So I wrote a sample app to try it out and it really worked out great. I thought of posting the source code and a little writeup about it so that it would be useful for others as well.
Setting up webview
The first thing that we have to do is to setup webview, which will be rendering the HTML page, on which we will be drawing the graph. You can add the webview control to your android layout.xml file using the following code.
Once it is added to your layout.xml page, you can access it in your activity using the following code.
Adding the HTML page to assets folder
Also add the flot and jQuery files into the /assets folder and refer to them with relative urls in your HTML file. You can also checkout the HTML file that I have created for reference.
Once you add the HTML file, you can load it in your webview using the following code snippet.
Check out the StatsGraphHandler class in my sample project for reference.
Enjoy your graph
That’s it 🙂 Fire up your app and you can see the excellent graph generated.
You can also add some buttons in the HTML page, which can directly interact with the graph. For other options, check out flot’s documentation.
You can download the complete code of the sample app that I created from my github account.