This code helps to draw a chart in your application using 'AChartEngine' charting library. There are various other charting libaray in Android like:
But here we will go with AChartEngine, AChartEngine supports the following chart types:
- lineChart
- Area Chart
- Scatter Chart
- Time Chart
- Bar Chart
- Pie Chart
- Bubble Chart
- Doughnut Chart
- Range (high-low) bar chart
- dial chart / gauge
- combined ( any combinatiob of line, cubic line, scatter, bar, range bar, bubble ) chart
- cubic line chart
Follow the steps mentioned below for Importing that library into your project:
- First download that library from the above link.
- Now create a folder named "libs" in your project and copy paste the achartengine.jar file inside the libs folder.
- Now Right click on the project name -> Properties -> Java Build Path -> Under Libraries tab -> Add Jar -> click on your project name -> libs -> achartengine.jar -> OK
- Now you have successfully Imported achartengine.jar file into the application.
- Now write the below code in java class:
Here I have created a file (source file) named aChartExample
public class aChart_Example {
private GraphicalView mChartView2;
private GraphicalView mChartView3;
static int count=5;
int[] Mycolors = new int[] { Color.RED, Color.DKGRAY, Color.BLUE, 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("Pets");
categorySeries.add("Dogs", 5);
categorySeries.add("Cats", 6);
categorySeries.add("Birds", 8);
categorySeries.add("Fish", 23);
categorySeries.add("Other Pets", 40);
mChartView2=ChartFactory.getPieChartView(context, categorySeries,renderer);
parent.addView(mChartView2);
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;
}
}
And please refer the activity main class as:
public class MyAppActivity extends Activity {
RelativeLayout LayoutToDisplayChart;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutToDisplayChart=(RelativeLayout)findViewById(R.id.relative_layout1);
Intent achartIntent = new aChart_Example().execute(MyAppActivity.this,LayoutToDisplayChart);
}
}
The Output of the above code is :
Comments
Post a Comment