Membuat Chart di Android, Aplikasi Grafik Android Menggunakan AChartEngine

0
5:58 AM

Fitur Chart atau Grafik termasuk fitur tambahan yang paling banyak digunakan di suatu Aplikasi. Begitu juga dengan di Android. Masalahnya adalah di Android tidak menyediakan Komponen Grafik (Chart) secara Default. Solusinya kita gunakan Chart Component dari luar yaitu AChartEngine. Dapat didownload di http://code.google.com/p/achartengine/.

Pertama buat project Android seperti biasa. Kemudian kita letakkan file library AChartEngine, misal yang penulis gunakan adalah achartengine-1.0.0.jar, dicopy dari Explorer, buka Eclipse, buka folder libs di project yang sedang dibuat kemudian Paste.

Setelah itu tuliskan kode program di MainActivity.java sebagai berikut :

package com.example.androidchart;

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.database.Cursor;
//import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.LinearLayout;

// http://cariprogram.blogspot.com
// nuramijaya@gmail.com

public class MainActivity extends Activity {
// protected Cursor cursor;
// SQLHelper dbHelper;

private GraphicalView mChart;

private XYSeries visitsSeries ;
private XYMultipleSeriesDataset dataset;

private XYSeriesRenderer visitsRenderer;
private XYMultipleSeriesRenderer multiRenderer;

public double[] arrnilai = {18,16,13,12,10};
public String[] arrurutan = {"1", "2", "3", "4", "5"}; //"14/4", "18/4", "24/4", "30/4", "7/5"};
public String[] arrlabel = {"ASII", "TLKM", "UNVR", "UNTR", "AALI"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
/*        dbHelper = new SQLHelper(this);
        
        SQLiteDatabase db = dbHelper.getReadableDatabase();

cursor = db.rawQuery("SELECT * FROM histori WHERE id_member = '" + MainActivity.idlogin + "' ORDER BY id_histori ASC",null);

arrlemak = new double[cursor.getCount()];
arrurutan = new String[cursor.getCount()];
arrtgl = new String[cursor.getCount()];
cursor.moveToFirst();
for (int cc=0; cc < cursor.getCount(); cc++)
{
cursor.moveToPosition(cc);
arrlemak[cc] = Double.parseDouble(cursor.getString(2).toString());
arrurutan[cc] = String.valueOf(cc+1);
arrtgl[cc] = cursor.getString(4).toString();
}
*/        
        // Setting up chart
        setupChart();
        
        // Start plotting chart
        new ChartTask().execute();
        
    }
    
    private void setupChart(){
    
     // Creating an  XYSeries for Visits
     visitsSeries = new XYSeries("% kenaikan harga saham");
    
    
     // 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.rgb(255, 0, 255));
     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("% kenaikan harga saham");
     multiRenderer.setXTitle("kode saham");
     multiRenderer.setYTitle("kenaikan harga");
     multiRenderer.setZoomButtonsVisible(true);
     multiRenderer.setXLabels(0);
    
     multiRenderer.setXAxisMin(0);
     multiRenderer.setXAxisMax(5);
    
     multiRenderer.setYAxisMin(0);
     multiRenderer.setYAxisMax(40);
    
     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{

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

values[0] = arrurutan[i]; // Integer.toString(i);
values[1] = String.valueOf(arrnilai[i]); //Integer.toString(visits);
values[2] = arrlabel[i];

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

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

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


Buat layout tampilan di activity_main.xml sebagai berikut :



    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
   
        android:id="@+id/tv_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Android Chart" />
    
   
        android:id="@+id/chart_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title" >
        
   





Untuk AndroidManifest.xml tidak perlu dirubah atau ditambah :



    package="com.example.androidchart"
    android:versionCode="1"
    android:versionName="1.0" >

   
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

   
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
       
            android:name="com.example.androidchart.MainActivity"
            android:label="@string/app_name" >
           
               

               
           


       
   



Hasilnya :


Project selengkapnya download disini. Jika ada yang kesulitan ini cara downloadnya

Semoga berguna :)

Sumber : http://cariprogram.blogspot.com/2013/04/android-chart-grafik-menggunakan-achartengine.html

About the author

Hanya Pecinta Seni ~
Tukang kode ~

0 komentar: