Android Dynamic Chart using AChartEngine

October 25, 2012
By

Dynamic chart is a user friendly mechanism to depict information to user in a real time system. In Android we can easily generate dynamic charts using AChartEngine library. This article exemplifies how to draw a dynamic chart in an Android application using AChartEngine library.

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 “AChartEngineDynamicChart”

Create a new Android Application project

Figure 1 : Create a new Android Application project


2. Design an 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">AChartEngineDynamicChart</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">AChartEngineDynamicChart</string>
    <string name="str_tv_title">A Dynamic Graph</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/achartenginedynamicchart/MainActivity.java


package in.wptrafficanalyzer.achartenginedynamicchart;

import java.util.Random;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.chart.PointStyle;
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.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

    private GraphicalView mChart;

    private XYSeries visitsSeries ;
    private XYMultipleSeriesDataset dataset;

    private XYSeriesRenderer visitsRenderer;
    private XYMultipleSeriesRenderer multiRenderer;

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

        // Setting up chart
        setupChart();

        // Start plotting chart
        new ChartTask().execute();

    }

    private void setupChart(){

        // Creating an  XYSeries for Visits
        visitsSeries = new XYSeries("Unique Visitors");

        // Creating a dataset to hold each series
        dataset = new XYMultipleSeriesDataset();
        // Adding Visits Series to the dataset
        dataset.addSeries(visitsSeries);

        // Creating XYSeriesRenderer to customize visitsSeries
        visitsRenderer = new XYSeriesRenderer();
        visitsRenderer.setColor(Color.WHITE);
        visitsRenderer.setPointStyle(PointStyle.CIRCLE);
        visitsRenderer.setFillPoints(true);
        visitsRenderer.setLineWidth(2);
        visitsRenderer.setDisplayChartValues(true);

        // Creating a XYMultipleSeriesRenderer to customize the whole chart
        multiRenderer = new XYMultipleSeriesRenderer();

        multiRenderer.setChartTitle("Visits Chart");
        multiRenderer.setXTitle("Seconds");
        multiRenderer.setYTitle("Count");
        multiRenderer.setZoomButtonsVisible(true);

        multiRenderer.setXAxisMin(0);
        multiRenderer.setXAxisMax(10);

        multiRenderer.setYAxisMin(0);
        multiRenderer.setYAxisMax(10);

        multiRenderer.setBarSpacing(2);

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

        // Getting a reference to LinearLayout of the MainActivity Layout
        LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);

        mChart = (GraphicalView) ChartFactory.getBarChartView(getBaseContext(), dataset, multiRenderer, Type.DEFAULT);

        // Adding the Line Chart to the LinearLayout
        chartContainer.addView(mChart);
    }

    private class ChartTask extends AsyncTask<Void, String, Void>{

        // Generates dummy data in a non-ui thread
        @Override
        protected Void doInBackground(Void... params) {
            int i = 0;
            try{
                do{
                    String [] values = new String[2];
                    Random r = new Random();
                    int visits = r.nextInt(10);

                    values[0] = Integer.toString(i);
                    values[1] = Integer.toString(visits);

                    publishProgress(values);
                    Thread.sleep(1000);
                    i++;
                }while(i<=10);
                    }catch(Exception e){ }
                return null;
            }

            // Plotting generated data in the graph
            @Override
            protected void onProgressUpdate(String... values) {
                visitsSeries.add(Integer.parseInt(values[0]), Integer.parseInt(values[1]));
                mChart.repaint();
            }
        }

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


14. Screenshot of the application

Dynamic Chart in Action

Figure 5 : Dynamic Chart in Action


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

8 Responses to Android Dynamic Chart using AChartEngine

  1. Nitish SIngla on June 7, 2013 at 6:01 pm

    Hello george,
    thanks for good-one Code for plotting Graphs using ChartEngine Library.

  2. Nikol on June 27, 2013 at 12:40 am

    Can I put 3 diferent Dynamic Charts on the same screen?

  3. harshad on September 10, 2013 at 8:40 pm

    Hi George,
    Im working on ECG project. Im receiving ECG pulses via serial Bluetooth attached to micro-controller.
    I want to store this real-time ECG graph on SD card. So, is it possible to 1)Show this ecg via Bluetooth in real-time
    2)how to store this a chart engine graph on SD card ?
    Thanks in advance

    Harshad

    • praveen on March 17, 2016 at 11:51 am

      did u got the solution for it,

  4. Ash on September 23, 2014 at 6:11 pm

    Can we achieve the same using Google Chart APIs ? I actually want to plot ECG waveform data, but I m not sure whether I will be having network connectivity.

  5. rohan on January 2, 2015 at 12:10 pm

    hello sir
    i m rohan bhnadri i m saying specially thanks to you

  6. Abraham on March 5, 2015 at 6:57 am

    Thanks so much for this example, it helped me a lot!!!

  7. fred on May 24, 2015 at 2:22 am

    Sir,I want to say thanks for the brilliant work done here.

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