Android Tutorial- Drawing AChartEngine Bar Chart with Example - Truiton
Skip to content

Android Tutorial- Drawing AChartEngine Bar Chart with Example

box design

As I said earlier all business applications are required to display some amount of graphical data, steps in Android AChartEngine Library. At Truiton our specialization is development of business mobile apps, therefore I thought to share some knowledge about it. In one of my previous tutorials I suggested a way to display graphical data with Google Charts, but it had a major draw back i.e. it required internet connectivity. To overcome this here I suggest we use Android AChartEngine, which is a charting library licensed under Apache License 2.0.

This Android AChartEngine Tutorial is the final addition to my series of tutorials on displaying charts on Android. This tutorial is number four in the list below:

  1. Google Chart Tools- Latest Chart Tools – Android Tutorial- Google Chart Tools
  2. Google Chart Tools: Image Tools- Deprecated – Android Tutorial- Google Chart Tools Image API
  3. AFreeChart- Android Tutorial- AFreeChart
  4. AChartEngine- Android Tutorial- Drawing AChartEngine Bar Chart with Example
  5. MPAndroidChart – Android MP Chart Library

Android AChartEngine Library is a free library which can be used to display graphs/charts on any Android OS based devices. AChartEngine supports many chart types like: Line Chart, Area Chart, Scatter Chart, Time Chart, Bar Chart, Pie Chart, Bubble Chart, Doughnut Chart, Range(high-low) Bar Chart, Dial/Gauge Chart, Combined Chart, and Cubic Line Chart. One of the most intriguing feature of Android AChartEngine is that it can combine all these charts into a single chart and can use multiple data series.

For this Android AChartEngine tutorial I am using library version 1.0.0 which is compatible for all android devices above 1.6 version. This could be downloaded from here:

http://achartengine.googlecode.com/files/achartengine-1.0.0.jar

This a highly stable release which can display thousands of values in a single graph, while maintaining the smoothness in interaction with graph. Now to start plotting the graph all we have to do is include the above .jar file in our project’s build path.

As this tutorial is an introduction to Android AChartEngine I am only going to show how to create an independent class and display bar charts. For this purpose lets create a TruitonAChartEngineActivity.java class as MAIN LAUNCHER class.

In that class lets create a method for data set in our Android AChartEngine bar chart:

 private XYMultipleSeriesDataset getTruitonBarDataset() {
 XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
 final int nr = 4;
 Random r = new Random();
 ArrayList<String> legendTitles = new ArrayList<String>();
 legendTitles.add("Sales");
 legendTitles.add("Expenses");
 for (int i = 0; i < SERIES_NR; i++) {
 CategorySeries series = new CategorySeries(legendTitles.get(i));
 for (int k = 0; k < nr; k++) {
 series.add(100 + r.nextInt() % 100);
 }
 dataset.addSeries(series.toXYSeries());
 }
 return dataset;
 }

Next to display Android AChartEngine bar chart we need to create a bars renderer :

 public XYMultipleSeriesRenderer getTruitonBarRenderer() {
 XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
 renderer.setAxisTitleTextSize(16);
 renderer.setChartTitleTextSize(20);
 renderer.setLabelsTextSize(15);
 renderer.setLegendTextSize(15);
 renderer.setMargins(new int[] { 30, 40, 15, 0 });
 SimpleSeriesRenderer r = new SimpleSeriesRenderer();
 r.setColor(Color.BLUE);
 renderer.addSeriesRenderer(r);
 r = new SimpleSeriesRenderer();
 r.setColor(Color.RED);
 renderer.addSeriesRenderer(r);
 return renderer;
 }

All this code would look a little more in place inside the whole class:

package com.truiton.myachartengine;

import java.util.ArrayList;
import java.util.Random;

import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.view.Menu;

public class TruitonAChartEngineActivity extends Activity {
 private static final int SERIES_NR = 2;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_truiton_achart_engine);
 XYMultipleSeriesRenderer renderer = getTruitonBarRenderer();
 myChartSettings(renderer);
 Intent intent = ChartFactory.getBarChartIntent(this, getTruitonBarDataset(), renderer, Type.DEFAULT);
 startActivity(intent);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.truiton_achart_engine, menu);
 return true;
 }

 private XYMultipleSeriesDataset getTruitonBarDataset() {
 XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
 final int nr = 4;
 Random r = new Random();
 ArrayList<String> legendTitles = new ArrayList<String>();
 legendTitles.add("Sales");
 legendTitles.add("Expenses");
 for (int i = 0; i < SERIES_NR; i++) {
 CategorySeries series = new CategorySeries(legendTitles.get(i));
 for (int k = 0; k < nr; k++) {
 series.add(100 + r.nextInt() % 100);
 }
 dataset.addSeries(series.toXYSeries());
 }
 return dataset;
 }

 public XYMultipleSeriesRenderer getTruitonBarRenderer() {
 XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
 renderer.setAxisTitleTextSize(16);
 renderer.setChartTitleTextSize(20);
 renderer.setLabelsTextSize(15);
 renderer.setLegendTextSize(15);
 renderer.setMargins(new int[] { 30, 40, 15, 0 });
 SimpleSeriesRenderer r = new SimpleSeriesRenderer();
 r.setColor(Color.BLUE);
 renderer.addSeriesRenderer(r);
 r = new SimpleSeriesRenderer();
 r.setColor(Color.RED);
 renderer.addSeriesRenderer(r);
 return renderer;
 }

 private void myChartSettings(XYMultipleSeriesRenderer renderer) {
 renderer.setChartTitle("Truiton's Performance by AChartEngine BarChart");
 renderer.setXAxisMin(0.5);
 renderer.setXAxisMax(10.5);
 renderer.setYAxisMin(0);
 renderer.setYAxisMax(210);
 renderer.addXTextLabel(1, "2010");
 renderer.addXTextLabel(2, "2011");
 renderer.addXTextLabel(3, "2012");
 renderer.addXTextLabel(4, "2013");
 renderer.setYLabelsAlign(Align.RIGHT);
 renderer.setBarSpacing(0.5);
 renderer.setXTitle("Years");
 renderer.setYTitle("Performance");
 renderer.setShowGrid(true);
     renderer.setGridColor(Color.GRAY);
     renderer.setXLabels(0); // sets the number of integer labels to appear
 }

}

As you can see in this class I have added another method called myChartSettings() which can be used to set the various graphical properties of Android AChartEngine bar chart. As a whole this class would display a graph in org.achartengine.GraphicalActivity. Yes this is surprisingly true as Android AChartEngine is an Intent based library, all the charts are displayed in GraphicalActivity. Therefore make sure you add this in your Android Manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.truiton.myachartengine"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.truiton.myachartengine.TruitonAChartEngineActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="org.achartengine.GraphicalActivity" />
    </application>

</manifest>

After all these steps your Android AChartEngine graph/chart would look somthing like this:

The part I liked about Android AChartEngine library is that it creates beautiful smooth scrolling charts. And even better- it could be customized to look like whatever you want it to look like. The project page of AChartEngine states that they are going to add new chart/graph types to this library in following releases, lets hope they make them even more interactive. This tutorial concludes my series on displaying charts on Android. If you find this interesting share this on Facebook, Google+ and like our Facebook page to stay connected with us.

Tags:

29 thoughts on “Android Tutorial- Drawing AChartEngine Bar Chart with Example”

    1. Hi Ajay,

      yes it is possible, you can do following changes in myChartSettings method
      change renderer.setYAxisMin(0) to renderer.setYAxisMin(10) – This way visible y axis would be from 10.
      add renderer.addYTextLabel(10, “10”) – To add a label for 10
      further include renderer.setPanEnabled(true, false) – This way chart wont scroll in Y axis, meaning user would see only 10 as first value.

      Hope this helps

  1. hello,
    I followed your tutorial. I want to use data from my sqlite to plot the graph. How can I replace this with my sqlite columns?
    for (int i = 0; i < SERIES_NR; i++)
    {
    CategorySeries series = new CategorySeries(legendTitles.get(i));
    for (int k = 0; k < nr; k++)
    {
    series.add(100 + r.nextInt() % 100);
    }
    }

    1. Hi Pooja,

      In this SERIES_NR is the number of columns to display, and series.add(YOUR_NUM_HERE); is the method used to insert values, that are shown on chart. So you can get values from your SQLite DB and pass them as an argument instead of YOUR_NUM_HERE. Hope this helps.

    1. hi,

      menu.xml is just file to define context menus in an app, for this tutorial you can remove the whole block of onCreateOptionsMenu(Menu menu). This will solve your issue.

  2. Hy, can you please make a good Tutorial like this for RangeBarChart with AchartEngine?
    I Searched a fes days, but I can’t find a tutorial for drawing a RangeBarChart with AchartEngine.

    Regards
    Mike

  3. Hi, how can I rotate the values that are displayed on top of every bar. I know that we can rotate the Y-axis labels but I want to rotate the actual chart values displayed on top of the bar. Can you provide me a solution for that.
    Regards.

  4. Hi Mohit,

    I tried bar charts with aChartEngine library in android 4.4 device and its working fine now.My requirement is to drag anyone of the bar in bar chart and re-size it and the value should get updated.Is that possible with aChartEngine?If so please can u give me source code?since i’am very new to android.Thanks in advance.

  5. nice tutorial but i got error in this lines i am fetching values from database and display in graph

    legendTitles.add(“Expenses”);
    for (int i = 0; i < SERIES_NR; i++) {
    CategorySeries series = new CategorySeries(legendTitles.get(i));
    for (int k = 0; k < nr; k++) {
    series.add(100 + r.nextInt() % 100);

  6. 08-25 00:19:02.321: E/AndroidRuntime(771): FATAL EXCEPTION: main
    08-25 00:19:02.321: E/AndroidRuntime(771): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.expressMilk/com.expressMilk.MainActivity}: java.lang.NullPointerException
    08-25 00:19:02.321: E/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:221u;

  7. Thanks, achartengine is the best free chart library.
    If do you want show graph in a view of an activity, you can use the method: ChartFactory.getBarChartView with the same parameters and assign this result to a LinearLayout of your activity. 

  8. Hello Mohit,

    First of all, Thankyou for a valuable tutorial. Could you please provide the activity_truiton_achart_engine.xml file of the above project.I couldnot find it in the above source code.

    Thanks in Advance

    Regards,
    Aditya. J

    1. Hi Aditya,

      activity_truiton_achart_engine.xml is just a blank xml layout file, you can create this file by any name. No need to draw a layout. As AChartEngine is opened up in a separate activity. Hope this helps.

      -Mohit

  9. Hi, How to change the color of bar dynamically. let suppose i want to change the color of bar whose value is greater then 25

  10. Hi Mohit, thx for this tutorial, I have a question.
    Can the chart be displayed in a Fragment? With other contents i.e. other fragments for detailed info.
    In my case I need to show two fragments, the top one is the fragment with a pie graph, the bottom a fragment with a list view for the details.

    Thx man!

Leave a Reply

Your email address will not be published. Required fields are marked *