Android Drawing Time Chart with TimeSeries in AChartEngine

October 23, 2012
By

In this article, we will create an Android application which demonstrates how to plot a time chart using AChartEngine library. This graph plots a visits vs views chart where visits and views are drawn using TimeSeries data.

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

Create a new Android Application project namely "AChartEngineTimeSeries"

Figure 1 : Create a new Android Application project namely "AChartEngineTimeSeries"


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">AChartEngineTimeSeries</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">AChartEngineTimeSeries</string>
    <string name="str_tv_title">Time Series 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/achartenginelinechartcustomlayoutclick/MainActivity.java


package in.wptrafficanalyzer.achartenginetimeseries;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

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;

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

    private void openChart(){

        int count = 5;
        Date[] dt = new Date[5];
        for(int i=0;i<count;i++){
            GregorianCalendar gc = new GregorianCalendar(2012, 10, i+1);
            dt[i] = gc.getTime();
        }

        int[] visits = { 2000,2500,2700,2100,2800};
        int[] views = {2200, 2700, 2900, 2800, 3200};

        // Creating TimeSeries for Visits
        TimeSeries visitsSeries = new TimeSeries("Visits");

        // Creating TimeSeries for Views
        TimeSeries viewsSeries = new TimeSeries("Views");

        // Adding data to Visits and Views Series
        for(int i=0;i<dt.length;i++){
            visitsSeries.add(dt[i], visits[i]);
            viewsSeries.add(dt[i],views[i]);
        }

        // Creating a dataset to hold each series
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

        // Adding Visits Series to the dataset
        dataset.addSeries(visitsSeries);

        // Adding Visits Series to dataset
        dataset.addSeries(viewsSeries);

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

        // Creating XYSeriesRenderer to customize viewsSeries
        XYSeriesRenderer viewsRenderer = new XYSeriesRenderer();
        viewsRenderer.setColor(Color.YELLOW);
        viewsRenderer.setPointStyle(PointStyle.CIRCLE);
        viewsRenderer.setFillPoints(true);
        viewsRenderer.setLineWidth(2);
        viewsRenderer.setDisplayChartValues(true);

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

        multiRenderer.setChartTitle("Visits vs Views Chart");
        multiRenderer.setXTitle("Days");
        multiRenderer.setYTitle("Count");
        multiRenderer.setZoomButtonsVisible(true);

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

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

        // Creating a Time Chart
        mChart = (GraphicalView) ChartFactory.getTimeChartView(getBaseContext(), dataset, multiRenderer,"dd-MMM-yyyy");

        multiRenderer.setClickEnabled(true);
        multiRenderer.setSelectableBuffer(10);

        // Setting a click event listener for the graph
        mChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Format formatter = new SimpleDateFormat("dd-MMM-yyyy");

                SeriesSelection seriesSelection = mChart.getCurrentSeriesAndPoint();

                if (seriesSelection != null) {
                    int seriesIndex = seriesSelection.getSeriesIndex();
                    String selectedSeries="Visits";
                    if(seriesIndex==0)
                        selectedSeries = "Visits";
                    else
                        selectedSeries = "Views";

                    // Getting the clicked Date ( x value )
                    long clickedDateSeconds = (long) seriesSelection.getXValue();
                    Date clickedDate = new Date(clickedDateSeconds);
                    String strDate = formatter.format(clickedDate);

                    // Getting the y value
                    int amount = (int) seriesSelection.getValue();

                    // Displaying Toast Message
                    Toast.makeText(
                        getBaseContext(),
                        selectedSeries + " on "  + strDate + " : " + amount ,
                        Toast.LENGTH_SHORT).show();
                    }
                }
            });

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

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


14. Run the application

TimeChart in Action

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

6 Responses to Android Drawing Time Chart with TimeSeries in AChartEngine

  1. George on April 15, 2013 at 6:32 pm

    Hello and thanks for the posts!

    I wanted to ask (if you can tell me ) how to do this.

    I have in one activity an edit text field where the user enters some data and presses a button to save them in a file together with the current date.
    I use :
    ArrayList data=new ArrayList();
    ArrayList _date=new ArrayList();

    String _date = new SimpleDateFormat(“dd/MM/yyyy”).format(new Date()).toString();
    _date.add(thedate);
    double data=Double.parseDouble(value.getText().toString().trim());
    data.add(thedata);

    I press a button and save the data.

    Then , to start the linegraph activity I use:
    Intent i = new Intent();
    i.setClassName(this,LineGraph.class.getName());
    i.putExtra(“value”, data);
    i.putExtra(“date”, _date);
    this.startActivity(i);

    In LineGraph activity I don’t know how to load these data and use them to make the plot.

    I do :

    public class LineGraph extends Activity {

    private Double data;
    private String _date;

    public Double getThedata(){ return this.data;}
    public void setThedata(Double data){ this.data=data;}

    public String getDate(){ return this._date;}
    public void setDate(String _date){ this._date=_date;}

    String filename = “myfile.xls”;

    public void onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);

    Bundle extras=getIntent().getExtras();

    Double _data=extras.getDouble(“value”);
    setThedata(thedata);
    String date=extras.getString(“date”);
    setDate(date);

    startActivity(getIntent(this));

    }

    public Intent getIntent(Context context){

    Double _data= getThedata();
    String date=getDate();

    ArrayList x =new ArrayList();
    ArrayList y =new ArrayList();

    readingfunction(); //read the file

    TimeSeries series = new TimeSeries(“Data”);
    for (int i=0;i<x.size();i++){
    series.add(x.get(i),y.get(i));

    }

  2. sravankumar on October 19, 2013 at 10:47 am

    this post is very useful.
    I want to put the x-axis as time with 5 mins of interval instead of date.
    i.e., the time in “hh:mm” format, i tried a lot but could not get it can u please guide me through. please.

  3. siddharth on March 18, 2015 at 4:56 pm

    hey i want to ask u that when i perform zoom operation in your graph it show multiple date with same value like “01-nov-2012 01-nov-2012 01-nov-2012″ and when i use zoom out it will show perfect value like shown in screen-shot it u can help me to solve this and one more thing can we fix vartical zoom and set only horizontal zoom plz replay here or mail me thanks !

  4. Chaithanya on December 1, 2015 at 2:42 pm

    Hi..this is a great work. How to combine time chart with other charts?

  5. Jhon on May 20, 2016 at 3:57 pm

    Hi how can i set initialZomm ?

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