Android Drawing Bar Chart using AChartEngine

October 20, 2012
By

In the article titled “Android Drawing Area Chart using AChartEngine“, we have plotted an area chart using AChartEngine in an Android application. In this article, we will create a bar chart using AChartEngine library.

In AChartEngine library, the only difference between area chart and bar chart is that,  area chart intent is created using the method ChartFactory.getLineChartIntent() and bar chart intent is created using the method ChartFactory.getBarChartIntent().

This application is developed using Eclipse (4.2.0) with ADT plugin (20.0.3) and Android SDK (R20.0.3).


1. Create a new Android application project namely “AChartEngineBarChart”

Create a new Android application project namely "AChartEngineBarChart"

Figure 1 : Create a new Android application project namely "AChartEngineBarChart"


2. Design application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity to define the class MainActivity

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete Android Support Library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Download the latest version of AChartEngine library ( jar file ) from here


7. Copy the downloaded library file to “libs” directory of the project


8. Update the file res/values/strings.xml


<resources>
    <string name="app_name">AChartEngineBarChart</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">AChartEngineBarChart</string>
    <string name="str_btn_chart">Income vs Expense Bar Chart</string>
</resources>


9. Update the layout of the MainActivity in the file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btn_chart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/str_btn_chart"
        tools:context=".MainActivity" />
</RelativeLayout>


10. Update the file res/values/styles.xml

<pre><resources>
    <style name="AppTheme" parent="android:Theme" />
</resources></pre>

11. Update the file res/values-v11/styles.xml

<pre><resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources></pre>

12. Update the file res/values-v14/styles.xml

<pre><resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources></pre>

13. Update the class MainActivity in the file src/in/wptrafficanalyzer/achartenginebarchart/MainActivity.java


package in.wptrafficanalyzer.achartenginebarchart;

import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.MultipleCategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private String[] mMonth = new String[] {
        "Jan", "Feb" , "Mar", "Apr", "May", "Jun",
        "Jul", "Aug" , "Sep", "Oct", "Nov", "Dec"
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting reference to the button btn_chart
        Button btnChart = (Button) findViewById(R.id.btn_chart);

        // Defining click event listener for the button btn_chart
        OnClickListener clickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Draw the Income vs Expense Chart
                openChart();
            }
        };

        // Setting event click listener for the button btn_chart of the MainActivity layout
        btnChart.setOnClickListener(clickListener);

    }

    private void openChart(){
        int[] x = { 0,1,2,3,4,5,6,7 };
        int[] income = { 2000,2500,2700,3000,2800,3500,3700,3800};
        int[] expense = {2200, 2700, 2900, 2800, 2600, 3000, 3300, 3400 };

        // Creating an  XYSeries for Income
        XYSeries incomeSeries = new XYSeries("Income");
        // Creating an  XYSeries for Expense
        XYSeries expenseSeries = new XYSeries("Expense");
        // Adding data to Income and Expense Series
        for(int i=0;i<x.length;i++){
            incomeSeries.add(i,income[i]);
            expenseSeries.add(i,expense[i]);
        }

        // Creating a dataset to hold each series
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        // Adding Income Series to the dataset
        dataset.addSeries(incomeSeries);
        // Adding Expense Series to dataset
        dataset.addSeries(expenseSeries);

        // Creating XYSeriesRenderer to customize incomeSeries
        XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
        incomeRenderer.setColor(Color.rgb(130, 130, 230));
        incomeRenderer.setFillPoints(true);
        incomeRenderer.setLineWidth(2);
        incomeRenderer.setDisplayChartValues(true);

        // Creating XYSeriesRenderer to customize expenseSeries
        XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
        expenseRenderer.setColor(Color.rgb(220, 80, 80));
        expenseRenderer.setFillPoints(true);
        expenseRenderer.setLineWidth(2);
        expenseRenderer.setDisplayChartValues(true);

        // Creating a XYMultipleSeriesRenderer to customize the whole chart
        XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
        multiRenderer.setXLabels(0);
        multiRenderer.setChartTitle("Income vs Expense Chart");
        multiRenderer.setXTitle("Year 2012");
        multiRenderer.setYTitle("Amount in Dollars");
        multiRenderer.setZoomButtonsVisible(true);
        for(int i=0; i< x.length;i++){
            multiRenderer.addXTextLabel(i, mMonth[i]);
        }

        // Adding incomeRenderer and expenseRenderer to multipleRenderer
        // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
        // should be same
        multiRenderer.addSeriesRenderer(incomeRenderer);
        multiRenderer.addSeriesRenderer(expenseRenderer);

        // Creating an intent to plot bar chart using dataset and multipleRenderer
        Intent intent = ChartFactory.getBarChartIntent(getBaseContext(), dataset, multiRenderer, Type.DEFAULT);

        // Start Activity
        startActivity(intent);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


14. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.achartenginebarchart"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <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>


15. Run the application

Displaying Bar Chart using AChartEngine library

Figure 5 : Displaying Bar Chart using AChartEngine library


16. Download


17. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

17 Responses to Android Drawing Bar Chart using AChartEngine

  1. Zubair on December 30, 2012 at 1:23 pm

    Hey.
    thanks for sharing this.
    +1 for that its up to date.
    +1 for sharing the source code.
    I visited a lot of blogs for a Bar Chart but none of them shared the source code and most of them are outdated.
    Keep up the Good work

  2. Naseeb Arora on January 2, 2013 at 4:58 pm

    Type.Default is not recognized.
    Suggest ?

    • george on January 2, 2013 at 5:32 pm

      Please check the case of “DEFAULT”

  3. Gratian on February 12, 2013 at 1:06 pm

    Hi, i would like to know if there is a way to arrange the value labels to the center of the bar.

    • george on February 13, 2013 at 4:27 pm

      If my understanding on your requirement is correct, then the method setChartValuesTextAlign(Align.CENTER) of XYSeriesRenderer will do for you.

  4. UDAY on March 20, 2013 at 1:23 am

    Clean Code.Keep it up.

  5. Ian on March 25, 2013 at 12:57 am

    How would you recommend I use values from a database to create a bar chart?

  6. Meriç AKGÜL on January 7, 2014 at 9:37 pm

    Hello George,
    Thanks for sharing this. What I am trying to do is stacked bar chart. I mean I want to add another value with different color on the existing value. How can I do this? Thanks in advance.

  7. Amin on August 27, 2014 at 6:49 pm

    Good Work , i like this tutorial .
    i want to know how to change the black background

  8. Monish on October 14, 2014 at 10:03 am

    Thanks a lot your code really helps me a lot and please will you share me a
    stacked bar chart

  9. Pankaj Gurjar on January 31, 2015 at 4:18 pm

    i want to know that how to change the background color(black) of this layout

  10. basmina on February 19, 2015 at 3:55 pm

    hi,site is very useful.i want the idea to move the bar from the chart on clicking it and it should go to a list view page.can anyone help me??

  11. Naveen on June 5, 2015 at 12:56 pm

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

  12. Shirish Kulkarni on July 8, 2015 at 10:11 pm

    Hey…Can you please share your Model class

  13. Karthikeyan V on July 23, 2015 at 3:53 pm

    How can we set bar color based on y-value (income or expense value). I need to set Red if income/exp >100 ,Blue 100>income/expense<50 and green for income/expense < 50. How can we achieve it ?

  14. Ankita on September 29, 2015 at 12:06 pm

    If there is single value for income and expense, then no bar is displayed on the chart

  15. vishkha gupta on January 6, 2016 at 5:10 pm

    Plz check the case of type.DEFAULT is error plz find it and tell me…

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner