Android Drawing Pie Chart using AChartEngine

October 21, 2012
By

In this article, we will create an Android application which plots a pie chart using AChartEngine library.

An extension to this article is available in the article titled “Android Pie Chart with click event in a Custom XML Layout using AChartEngine

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


1. Create an Android application project namely “AChartEnginePieChart”

Create a new Android Application Project namely "AChartEnginePieChart"

Figure 1 : Create a new Android Application Project namely "AChartEnginePieChart"


2. Design an application launcher icon

Design an application launcher icon

Figure 2 : Design an 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">AChartEnginePieChart</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Pie Chart Demo</string>
    <string name="str_btn_chart">Pie 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" />

</RelativeLayout>


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


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


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


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


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


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


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


package in.wptrafficanalyzer.achartenginepiechart;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

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 {

    @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(){

        // Pie Chart Section Names
        String[] code = new String[] {
            "Eclair & Older", "Froyo", "Gingerbread", "Honeycomb",
            "IceCream Sandwich", "Jelly Bean"
        };

        // Pie Chart Section Value
        double[] distribution = { 3.9, 12.9, 55.8, 1.9, 23.7, 1.8 } ;

        // Color of each Pie Chart Sections
        int[] colors = { Color.BLUE, Color.MAGENTA, Color.GREEN, Color.CYAN, Color.RED,
                        Color.YELLOW };

        // Instantiating CategorySeries to plot Pie Chart
        CategorySeries distributionSeries = new CategorySeries(" Android version distribution as on October 1, 2012");
        for(int i=0 ;i < distribution.length;i++){
            // Adding a slice with its values and name to the Pie Chart
            distributionSeries.add(code[i], distribution[i]);
        }

        // Instantiating a renderer for the Pie Chart
        DefaultRenderer defaultRenderer  = new DefaultRenderer();
        for(int i = 0 ;i<distribution.length;i++){
            SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
            seriesRenderer.setColor(colors[i]);
            seriesRenderer.setDisplayChartValues(true);
            // Adding a renderer for a slice
            defaultRenderer.addSeriesRenderer(seriesRenderer);
        }

        defaultRenderer.setChartTitle("Android version distribution as on October 1, 2012 ");
        defaultRenderer.setChartTitleTextSize(20);
        defaultRenderer.setZoomButtonsVisible(true);

        // Creating an intent to plot bar chart using dataset and multipleRenderer
        Intent intent = ChartFactory.getPieChartIntent(getBaseContext(), distributionSeries , defaultRenderer, "AChartEnginePieChartDemo");

        // 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.achartenginepiechart"
    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

A Pie Chart using AChartEngine Library

Figure 5 : A Pie 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: , , ,

24 Responses to Android Drawing Pie Chart using AChartEngine

  1. Rajkiran Bande on October 23, 2012 at 12:58 pm

    Awesome tutorial man. This is just like spoonfeeding. :P Hats off!!

    • george on October 23, 2012 at 2:24 pm

      :)

    • vivek on March 22, 2013 at 6:56 pm

      Excellent!!!! thanks for this code.. can we show percentage along with “%” sign

    • r on January 8, 2015 at 2:13 pm

      ok

    • manick on July 9, 2015 at 12:11 pm

      Hi, can you please tell me how to set a border color this pie chart?

    • manick on July 9, 2015 at 12:11 pm

      Hi, can you please tell me how to set a border color to this pie chart?

    • Srikanth on February 25, 2016 at 11:22 am

      How to dispplat tect on Piechart Slice

  2. July on January 3, 2013 at 1:02 pm

    Excellent !!!!! very useful !!!!

  3. Sanat on January 30, 2013 at 4:20 pm

    Greate , very simple than other :)

  4. Dude on February 7, 2013 at 3:57 am

    Great tnx!, is it possible to show the values for each slice?

  5. Abhiraj on April 9, 2013 at 5:42 pm

    How to make the pie chart clickable.. I want to start new activity on click of pie chart wedges…

  6. A on May 29, 2013 at 10:15 pm

    After i run the code once,and when i again try to run it the pie chart is directly displayed and not the main activity?why is dat? and how to fix it?

  7. s on June 11, 2013 at 2:18 pm

    Hii george,is it possible to change the position of the legends?

  8. anu on February 16, 2014 at 5:20 am

    How to change the colors in pie chart to gradient colors depending on the values?

  9. Irfan Ali on March 20, 2014 at 3:23 pm

    nice………..lot of Thanks

  10. Stone on March 31, 2014 at 12:54 pm

    I want to show the lables on the bottom,and show the values on the pie chart。How to do it?

  11. Stone on March 31, 2014 at 12:57 pm

    I add the”seriesRenderer.setDisplayChartValues(true);” in the app ,but it’s not work! I’m in trouble……

    • krunal patel on April 14, 2014 at 6:26 pm

      bro i think you are using the older version of achartengine.
      try to get the new one. version1.1.0

  12. fazil on September 22, 2014 at 3:09 pm

    How to Control zoom in and Zoom out

  13. Favas on March 23, 2015 at 4:21 pm

    Excellent work

  14. Naveen on March 25, 2015 at 2:42 pm

    double[] distribution = { 3.9, 12.9, 55.8, 1.9, 23.7, 1.8 } ;

    suppose instead of that if i have the value for that array like

    double[] distribution = { 0, 0, 0, 0, 0, 0 } ;

    I want to show the pie chart graph there that showing zero value for each can i do this.Or can i simply so that pie chart graph having some default background color.

  15. jithin gopal on August 11, 2015 at 12:27 pm

    How to change the color of the indicator of the pie chart?

  16. mahesh on December 15, 2015 at 10:27 am

    HOW TO CREATE 3d PIE CHART IN ANDROID

  17. Manoj on April 12, 2016 at 1:28 pm

    hi
    how could we change label that are below customized

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