Android Pie Chart with click event in a Custom XML Layout using AChartEngine

October 24, 2012
By

This article is an extension to the article titled “Android Drawing Pie Chart using AChartEngine“, where we have created a pie chart graph using an intent. In this article, we will discuss how to create a pie chart in a custom xml layout with click event enabled.

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


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

Create a new Android application project

Figure 1 : Create a new Android application project


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">AChartEnginePieChartCustomLayoutClick</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">AChartEnginePieChartCustomLayoutClick</string>
    <string name="str_tv_title">AChartEngine  Click Demo</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" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_tv_title"
        android:gravity="center_horizontal" />

    <LinearLayout
        android:id="@+id/chart_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title" >
    </LinearLayout>

</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.Holo" />
</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/achartenginepiechartcustomlayoutclick/MainActivity.java


package in.wptrafficanalyzer.achartenginepiechartcustomlayoutclick;

import java.text.DecimalFormat;

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

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

    private GraphicalView mChart;
    private String[] code;

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

        // Ploting the chart
        openChart();
    }

    private void openChart(){

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

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

        // Color of each Pie Chart Slices
        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++){

            // Instantiating a render for the slice
            SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
            seriesRenderer.setColor(colors[i]);
            seriesRenderer.setDisplayChartValues(true);

            // Adding the renderer of a slice to the renderer of the pie chart
            defaultRenderer.addSeriesRenderer(seriesRenderer);
        }

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

        // Getting a reference to view group linear layout chart_container
        LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);

        // Getting PieChartView to add to the custom layout
        mChart = ChartFactory.getPieChartView(getBaseContext(), distributionSeries, defaultRenderer);

        defaultRenderer.setClickEnabled(true);//
        defaultRenderer.setSelectableBuffer(10);
        mChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SeriesSelection seriesSelection = mChart.getCurrentSeriesAndPoint();
                if (seriesSelection != null) {

                    // Getting the name of the clicked slice
                    int seriesIndex = seriesSelection.getPointIndex();
                    String selectedSeries="";
                    selectedSeries = code[seriesIndex];

                    // Getting the value of the clicked slice
                    double value = seriesSelection.getXValue();
                    DecimalFormat dFormat = new DecimalFormat("#.#");

                    // Displaying the message
                    Toast.makeText(
                        getBaseContext(),
                        selectedSeries + " : "  + Double.valueOf(dFormat.format(value)) + " % " ,
                        Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Adding the pie chart to the custom layout
        chartContainer.addView(mChart);
    }

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


14. Run the application

PieChart with Click Event using AChartEngine

Figure 5 : PieChart with Click Event using AChartEngine


15. Download


16. 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: , , ,

3 Responses to Android Pie Chart with click event in a Custom XML Layout using AChartEngine

  1. Saif Shaikh on August 28, 2013 at 3:41 pm

    Hello George. Your example above is really helpful. However I just had one question. How can I show the percentages inside the pieces of pie chart?

  2. Nick on January 7, 2014 at 10:48 pm

    I don’t know why but it crushes when I click on the chart.

  3. Puneet Ahuja on October 7, 2014 at 11:48 am

    Nice Man it was really nice code and very helpful too…
    Thanks

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