Sunday, 9 June 2013

Draw Graph in Android

Graph play a very important role in showing data in  Graphical view. User generally find comparison  in a graph  very interesting. It gives a clear view of something going up or down or how things related to each other or what is previous record  and is next coming forecast for that  etc.
  But in android there is no graph  related API . We can draw graph in android by using general  android  API.  The other way is to use third party graph library to draw the graph.  So  finally we have to two option
 (1.) Draw graph by using general android API  and
 (2.) Draw the graph by using Third party graph library
       (As  for Example AChartEngine, AndroidPlot, Google Chart , AFreeChart etc)

Here I am going to show a example of Pie chart  in both scenario  :
Firstly I am using case A ( by using general android API to draw a Graph)
These are the  4 files and class we need to draw the graph :-
  1. pie_chart_activity.xml ( pie chart view purpose)
  2. PieChartActivity.java ( main class to draw a pie chart )
  3. Piechart.java ( pie chart properties class)
  4. PieItem.java ( attributes class )
Step 1.
Create a Project in Your Eclipse IDE. Then copy and paste following file and java class in your application .
pie_chart_activity.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"
tools:context=".PieChartActivity" >

<LinearLayout
    android:id="@+id/pie_container"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:orientation="vertical" >
</LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignRight="@+id/pie_container"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" >

    <TextView
        android:id="@+id/parta"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#444544"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="PartA"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/partb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/parta"
        android:background="#878887"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="PartB"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/partc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/partb"
        android:background="#98967F"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="PartC"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/partd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/partc"
        android:background="#A1A1A1"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="PartD"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/parte"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/partd"
        android:background="#0000FF"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="PartE"
        android:textStyle="bold" />
</RelativeLayout>
PieChartActivity.java
package com.sks.mks.pieexample;
public class PieChartActivity extends Activity {

List<PieItem> piedata = new ArrayList<PieItem>(0);

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

  PieItem item;
  int maxCount = 0;
  int itemCount = 0;
  int items[] = { 20, 40, 10, 15, 5 };
  int colors[] = { -6777216, -16776961, -16711681, -12303292, -7829368 };
  String itemslabel[] = { "part A 100", "part B 200",
    "Part C 300", "Part D  400", "Part E 500" };
  for (int i = 0; i < items.length; i++) {
   itemCount = items[i];
   item = new PieItem();
   item.count = itemCount;
   item.label = itemslabel[i];
   item.color = colors[i];
   piedata.add(item);
   maxCount = maxCount + itemCount;
  }

  int size = 155;
  int BgColor = 0xffa11b1;
  Bitmap mBaggroundImage = Bitmap.createBitmap(size, size,Bitmap.Config.ARGB_8888);

  Piechart piechart = new Piechart(this);
  Piechart.setLayoutParams(new LayoutParams(size, size));
  piechart.setGeometry(size, size, 2, 2, 2, 2, 2130837504);
  piechart.setSkinparams(BgColor);
  piechart.setData(piedata, maxCount);
  piechart.invalidate();
  piechart.draw(new Canvas(mBaggroundImage));
  piechart = null;
  ImageView mImageView = new ImageView(this);
  mImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
  mImageView.setBackgroundColor(BgColor);
  mImageView.setImageBitmap(mBaggroundImage);
  LinearLayout finalLayout = (LinearLayout) findViewById(R.id.pie_container);
  finalLayout.addView(mImageView);
 }
}
Piechart.java
package com.sks.mks.pieexample;

public class Piechart {

public static final int WAIT = 0;
 public static final int IS_READY_TO_DRAW = 1;
 public static final int IS_DRAW = 2;
 private static final float START_INC = 30;
 private Paint mBagpaints = new Paint();
 private Paint mLinePaints = new Paint();

 private int mWidth;
 private int mHeight;
 private int mGapTop;
 private int mGapBottm;
 private int mBgcolor;
 private int mGapleft;
 private int mGapright;
 private int mState = WAIT;
 private float mStart;
 private float mSweep;
 private int mMaxConnection;
 private List<PieItem> mdataArray;

 public Piechart(Context context) {
  Log.w(" single cons ", " single cons");
 }

 public Piechart(Context context, AttributeSet attr) {
  Log.w(" double cons ", " double cons");
 }


 protected void onDraw(Canvas canvas) {
  if (mState != IS_READY_TO_DRAW) {
   return;
  }
  canvas.drawColor(mBgcolor);
  mBagpaints.setAntiAlias(true);
  mBagpaints.setStyle(Paint.Style.FILL);
  mBagpaints.setColor(0x88FF0000);
  mBagpaints.setStrokeWidth(0.0f);
  mLinePaints.setAntiAlias(true);
  mLinePaints.setColor(0xff000000);
  mLinePaints.setStrokeWidth(3.0f);
  mLinePaints.setStyle(Paint.Style.STROKE);
  RectF mOvals = new RectF(mGapleft, mGapTop, mWidth - mGapright, mHeight
    - mGapBottm);
  mStart = START_INC;
  PieItem item;
  for (int i = 0; i < mdataArray.size(); i++) {
   item = (PieItem) mdataArray.get(i);
   mBagpaints.setColor(item.color);
   mSweep = (float) 360* ((float) item.count / (float) mMaxConnection);
   canvas.drawArc(mOvals, mStart, mSweep, true, mBagpaints);
   canvas.drawArc(mOvals, mStart, mSweep, true, mLinePaints);
   mStart = mStart + mSweep;
  }

  mState = IS_DRAW;
 }

 public void setGeometry(int width, int height, int gapleft, int gapright,
   int gaptop, int gapbottom, int overlayid) {

  mWidth = width;
  mHeight = height;
  mGapleft = gapleft;
  mGapright = gapright;
  mGapBottm = gapbottom;
  mGapTop = gaptop;

 }

 public void setSkinparams(int bgcolor) {
  Log.w(" Set bg color  : ", bgcolor + "");
  mBgcolor = bgcolor;
 }

 public void setData(List<PieItem> data, int maxconnection) {
  mdataArray = data;
  mMaxConnection = maxconnection;
  Log.w(" Max Connection  ", maxconnection + " " + "  Adataarray :"
    + data.toString());
  mState = IS_READY_TO_DRAW;
 }

 public void setState(int state) {
  mState = state;
 }

 public int getColorValues(int index) {
  if (mdataArray == null) {
   return 0;
  }

  else if (index < 0)
   return ((PieItem) mdataArray.get(0)).color;
  else if (index > mdataArray.size())
   return ((PieItem) mdataArray.get(mdataArray.size() - 1)).color;
  else
   return ((PieItem) mdataArray.get(mdataArray.size() - 1)).color;

 }

}
PieItem.java
package com.sks.mks.pieexample;
public class PieItem {
 public int count, color;
 public float percent;
 public String label;
}

Now I am going to draw graph by using Third party library. Here i am using AchartEngin to draw graph :-
At first download AchartEngin and put it on libs folder of Your Eclipse project. You can download it from Here

Now  Create two java class in src and one  xml file in res folder.
1. DrawChart.java
2.GraphActivity.java
3. activity_graph.xml
copy and paste following code in your DrawChart.java
package com.sks.mks.piechart;

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.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.widget.RelativeLayout;

public class DrawChart {
private GraphicalView ChartView1;
private GraphicalView mChartView2;
static int count=5;
int[] Mycolors = new int[] { Color.RED, Color.parseColor("#FA58F4"),
Color.parseColor("#0B0B61"),
Color.parseColor("#800080"),Color.parseColor("#008000"),Color.GRAY };
public Intent execute(Context context,RelativeLayout parent) {
int[] colors = new int[count];
for(int i=0;i<count;i++)
{
colors[i]=Mycolors[i];
}
DefaultRenderer renderer = buildCategoryRenderer(colors);
renderer.setPanEnabled(false);// Disable User Interaction
renderer.setLabelsColor(Color.BLACK);
renderer.setShowLabels(true);
//renderer.setChartTitle("Total Assets");
renderer.setLabelsTextSize(12);
CategorySeries categorySeries = new CategorySeries("Fruits");
categorySeries.add("Apple", 36);
categorySeries.add("Banana", 23);
categorySeries.add("Grapes", 30);
categorySeries.add("Guava", 8);
categorySeries.add("Orange", 3);
ChartView1=ChartFactory.getPieChartView(context, categorySeries,renderer);
parent.addView(ChartView1);
return ChartFactory.getPieChartIntent(context, categorySeries, renderer,null);
}
protected DefaultRenderer buildCategoryRenderer(int[] colors)
{
DefaultRenderer renderer = new DefaultRenderer();
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();

r.setColor(color);
renderer.addSeriesRenderer(r);
}
return renderer;
} 
} 
Now  put following code in GraphActivity.java
package com.sks.mks.piechart;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.RelativeLayout; 
public class GraphActivity extends Activity {
       RelativeLayout LayoutToDisplayChart;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_graph);
              LayoutToDisplayChart=(RelativeLayout)findViewById(R.id.relative);
              Intent achartIntent = new DrawChart().execute(GraphActivity.this, LayoutToDisplayChart);
                          
       }
}
lastly put following code in xml file:-
<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"
    tools:context=".GraphActivity" >
<RelativeLayout
android:id="@+id/relative"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</RelativeLayout>
</RelativeLayout> 
Happy Coding !!!

No comments:

Post a Comment

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...