chart values not showing properly for stack bar chart achartengine - android

I am creating Stacked bar chart using Achartengine library. The values doesn't show properly. I want want to show the chart value like this {20,20,20} at top of the bar and align to center.
Here is my code
dataset.addSeries(JumlahSeries);
dataset.addSeries(JumlahSeries1);
dataset.addSeries(FirstSeries);
final XYSeriesRenderer FirstRenderer = new XYSeriesRenderer();
Log.d("Error Here","29");
FirstRenderer.setColor(Color.BLUE);
FirstRenderer.setFillPoints(false);
FirstRenderer.setLineWidth(5);
FirstRenderer.setChartValuesTextSize(15);
FirstRenderer.setDisplayChartValues(false);
// Creating XYSeriesRenderer to customize expenseSeries
Log.d("Error Here","30");
final XYSeriesRenderer SecondRenderer = new XYSeriesRenderer();
SecondRenderer.setColor(Color.RED);
SecondRenderer.setFillPoints(false);
SecondRenderer.setLineWidth(5);
SecondRenderer.setDisplayChartValues(false);
SecondRenderer.setChartValuesTextSize(15);
Log.d("Error Here","31");
final XYSeriesRenderer ThirdRenderer = new XYSeriesRenderer();
ThirdRenderer.setFillPoints(false);
ThirdRenderer.setColor(Color.GREEN);
ThirdRenderer.setLineWidth(5);
ThirdRenderer.setDisplayChartValues(false);
ThirdRenderer.setChartValuesTextSize(15);
// Creating a XYMultipleSeriesRenderer to customize the whole chart
final XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
//zoomIn = new Zoom((GraphicalView) mChart, true, multiRenderer.getZoomRate());
//multiRenderer.setChartTitle("\n"+"\n"+ title);
multiRenderer.setChartTitleTextSize(20);
//multiRenderer.setXTitle("\n"+"\n"+"\n"+"\n"+"\n"+"\n"+"\n"+"\n"+"Laporan Pada :"+ DateToDisplay);
multiRenderer.setShowGridX(false);
multiRenderer.setShowLegend(true);
multiRenderer.setShowLabels(true);
multiRenderer.setAxisTitleTextSize(15);
multiRenderer.setMargins(new int[] { 70,70,25,25});
multiRenderer.setYTitle("Bilangan\n\n"+"\n"+"\n"+"\n");
multiRenderer.setZoomButtonsVisible(true);
multiRenderer.setBarSpacing(spacing);
multiRenderer.setYAxisMax(max);
multiRenderer.setYLabelsColor(0, Color.BLACK);
multiRenderer.setXLabelsColor(Color.BLACK);
multiRenderer.setXLabels(0);
multiRenderer.setPanEnabled(true, false);
double Xmax = 2;
if(StacktotalX.getTotal().size()<5){
Log.d("Error Here","32");
Xmax=StacktotalX.getTotal().size()*1.3;
}
multiRenderer.setXAxisMax(Xmax) ;
multiRenderer.setXAxisMin(-1) ;
multiRenderer.setLabelsTextSize(13);
multiRenderer.setZoomEnabled(true,false);
multiRenderer.setClickEnabled(true);
for (int i = 0; i < StacktotalX.getTotal().size(); i++)
{
Log.d("Error Here","33");
multiRenderer.addXTextLabel(i,StacktotalX.getTotal().get(i).toString());
Log.d("texl",StacktotalX.getTotal().get(i).toString());
}
multiRenderer.addSeriesRenderer(ThirdRenderer);
multiRenderer.addSeriesRenderer(SecondRenderer);
multiRenderer.addSeriesRenderer(FirstRenderer);
Log.d("Error Here","34");
mChart = ChartFactory.getBarChartView(getBaseContext(), dataset, multiRenderer, Pattern);
multiRenderer.setApplyBackgroundColor(true);
multiRenderer.setBackgroundColor(Color.TRANSPARENT);
multiRenderer.setMarginsColor(Color.TRANSPARENT);
multiRenderer.setLabelsColor(Color.BLACK);
mChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChart.getCurrentSeriesAndPoint();
if (seriesSelection != null) {
int seriesIndex = seriesSelection.getSeriesIndex();
String selectedSeries="Bilangan";
Log.d("seriesIndex",String.valueOf(seriesIndex));
// String yobject = [(int)seriesSelection.getXValue()-1];
// Getting the clicked Month
//String month = x[(int)seriesSelection.getXValue()-1];
// Getting the y value
int amount = (int) seriesSelection.getValue();
Log.d("amout",String.valueOf(amount));
Toast.makeText(
getBaseContext(),
selectedSeries + " in " + " : " + amount ,
Toast.LENGTH_SHORT).show();
}
}
});
// Start Activity*/
chartContainer.addView(mChart);
new Thread(new Runnable() {
public void run() {
long time = 0;
time = 9000/max;
Log.d("Error Here","35");
if(time>1.5){
time = (long) 1.5;
}if(time<0.5){
time = (long) 0.5;
}
int animation = 1;
Log.d("Error Here","36");
while(true){
boolean stop = true;
for(int k=0; k< StacktotalX.getTotal().size();k++){
// for(int k=0;k<jum1.size();k++)
// {
// JumlahSeries.add(k,jum1.get(tims));
// tims++;
// }
if(animation<= jum3.get(k)){
Log.d("Error Here","37");
FirstSeries.add(k,animation);
stop=false;
}
if(animation<= jum.get(k)){
Log.d("Error Here","38");
JumlahSeries1.add(k,animation);
stop=false;
}
if(animation<= jum1.get(k)){
Log.d("Error Here","39");
JumlahSeries.add(k,animation);
stop=false;
}
}
try {
Log.d("Error Here","40");
Thread.sleep(time);
Log.d("Error Here","4");
mChart.repaint();
}catch (InterruptedException e) {
e.printStackTrace();
}
animation++;
if(stop){
FirstSeries.clear();
JumlahSeries1.clear();
JumlahSeries.clear();
for(int y=0;y<StacktotalX.getTotal().size();y++)
{
FirstSeries.add(y,jum3.get(y));
JumlahSeries1.add(y, jum.get(y));
JumlahSeries.add(y, jum1.get(y));
}
FirstRenderer.setChartValuesSpacing(10);
FirstRenderer.setChartValuesTextAlign(Align.LEFT);
FirstRenderer.setDisplayChartValues(true);
FirstRenderer.getChartValuesTextAlign();
SecondRenderer.setChartValuesSpacing(10);
SecondRenderer.setChartValuesTextAlign(Align.CENTER);
SecondRenderer.setDisplayChartValues(true);
SecondRenderer.getChartValuesTextAlign();
ThirdRenderer.setChartValuesSpacing(10);
ThirdRenderer.setChartValuesTextAlign(Align.RIGHT);
ThirdRenderer.setDisplayChartValues(true);
ThirdRenderer.getChartValuesTextAlign();
mChart.repaint();
break;
}
}
}
}).start();*
This is my image that now is showing:-

Related

How to display refresh webservice value in achartengine line chart?

I have achartengine line graph, i successfully for displaying values from json webservice in line graph. But problem is when i callback asynctask then line graph display old values on x y axis. Not displaying the new values. Below is my code.
public void charDeclaration() {
// For chart
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
if (myChart == null) {
initializeChartNew();
myChart = ChartFactory.getLineChartView(this, dataset,
multiRenderer);
layout.addView(myChart);
} else {
myChart.repaint();
}
}
#SuppressWarnings("deprecation")
private void initializeChartNew() {
// Creating an XYSeries for Income
fromTemp = new XYSeries("Temperature");
for (int i = 0; i < temp_time.size(); i++) {
fromTemp.add(i, Double.parseDouble(temp_details.get(i)));
System.out.println("Temperature Details in Charts "
+ temp_details.get(i));
}
// Creating a dataset to hold each series
dataset = new XYMultipleSeriesDataset();
// Adding Income Series to the dataset
dataset.addSeries(fromTemp);
// Creating XYSeriesRenderer to customize incomeSeries
from_tempRenderer = new XYSeriesRenderer();
from_tempRenderer.setColor(Color.WHITE);
from_tempRenderer.setPointStyle(PointStyle.CIRCLE);
from_tempRenderer.setFillPoints(true);
from_tempRenderer.setLineWidth(2);
from_tempRenderer.setChartValuesTextSize(20);
from_tempRenderer.setDisplayChartValues(true);
// Creating XYSeriesRenderer to customize expenseSeries
// Creating a XYMultipleSeriesRenderer to customize the whole chart
multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setMargins(new int[] { 50, 50, 50, 50 });
multiRenderer.setYLabelsAlign(Align.RIGHT);
multiRenderer.setAxisTitleTextSize(20);
multiRenderer.setChartTitleTextSize(20);
multiRenderer.setLabelsTextSize(18);
multiRenderer.setLegendTextSize(18);
multiRenderer.setXLabels(0);
for (int k = 0; k < temp_date.size(); k++) {
multiRenderer.setChartTitle(temp_date.get(k));
System.out
.println("Temperature Date in Charts " + temp_date.get(k));
}
multiRenderer.setXTitle("Time");
multiRenderer.setYTitle("Temperature");
multiRenderer.setYLabelsPadding(5);
multiRenderer.setZoomButtonsVisible(true);
multiRenderer.setPointSize(5);
for (int i = 0; i < temp_time.size(); i++) {
multiRenderer.addXTextLabel(i, temp_time.get(i));
}
System.out.println("value of temp_details " + temp_details.size());
multiRenderer.removeSeriesRenderer(from_tempRenderer);
multiRenderer.addSeriesRenderer(from_tempRenderer);
}
Below is my AsyncTask
private class TemperatureDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity_New.this);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
// building_segment_id="";
/*
* temp_details.clear(); date_time.clear(); temp_date.clear();
* temp_time.clear();
*/
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
System.out
.println("Temp Building Seg ID" + building_segment_id);
// String temperature_url =
// "http://www.intelatrek.com:98/Service1.svc/TempratueList?BeconID=329%20King&Date=2015-04-09";
String temp_url = "http://db.stat-systems.co.nz:81/Service1.svc/TempratureList?BeconID="
+ building_segment_id + "&Date=2015-04-13";
System.out.println("BlucatID in Asynctask " + blucat_id);
System.out.println("building_segment_id in AsyncTask "
+ building_segment_id);
temp_details.clear();
date_time.clear();
temp_date.clear();
temp_time.clear();
JSONObject jObject = JSONParser.getJsonFromURL(temp_url);
tempjsonflag = jObject.getString("Flag");
JSONArray jArray = jObject.getJSONArray("TempTransList");
for (int i = 0; i < jArray.length(); i++) {
JSONObject job = jArray.getJSONObject(i);
String BuildingId = job.getString("BuildingId");
String BuildingSegmentId = job
.getString("BuildingSegmentId");
// String Customer_ID = job.getString("Customer_ID");
String DateTime = job.getString("DateTime");
// String InnerLocationId =
// job.getString("InnerLocationId");
String Temp_Date = job.getString("TempDate");
String Temp_Time = job.getString("TempTime");
String Temperature = job.getString("Temperature");
temp_details.add(Temperature);
date_time.add(DateTime);
temp_date.add(Temp_Date);
temp_time.add(Temp_Time);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog != null) {
pDialog.dismiss();
}
for (int i = 0; i < temp_details.size(); i++) {
System.out
.println("Temperature Details " + temp_details.get(i));
System.out.println("Temperature Date Time " + date_time.get(i));
System.out.println("Temperature Temp Date " + temp_date.get(i));
System.out.println("Temperature Temp Time " + temp_time.get(i));
}
System.out.println("Temp Details " + temp_details.size());
System.out.println("Temp Date Time " + date_time.size());
System.out.println("Temp Temp Date " + temp_date.size());
System.out.println("Temp Temp Time " + temp_time.size());
System.out.println("Temp JSON FLAG " + tempjsonflag);
// if(tempjsonflag.equals("Success")){
if (tempe_detail.toString().equals("")) {
temp_textview_temperature.setVisibility(View.GONE);
temp_textview_notfound.setVisibility(View.VISIBLE);
imageview_degree.setVisibility(View.GONE);
/*
* LinearLayout layout = (LinearLayout)
* findViewById(R.id.chart);
*/
chart.setVisibility(View.GONE);
} else {
temp_textview_notfound.setVisibility(View.GONE);
temp_textview_temperature.setVisibility(View.VISIBLE);
temp_textview_temperature.setText(tempe_detail);
temp_textview_temperature.setTextSize(70);
imageview_degree.setVisibility(View.VISIBLE);
// temp_textview_temperature.setLayoutParams(llp);
/*
* LinearLayout layout = (LinearLayout)
* findViewById(R.id.chart);
*/
chart.setVisibility(View.VISIBLE);
charDeclaration();
}
if (temp_textview_temperature.getText().toString().equals("1")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("2")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("3")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("4")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("5")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("6")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("7")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("8")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("9")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else {
temp_textview_temperature.setPadding(0, 0, 0, 0);
}
int dip = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, (float) 1, getResources()
.getDisplayMetrics());
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int widthPixels = dm.widthPixels;
int heightPixels = dm.widthPixels;
float scaleFactor = dm.density;
float widthInches = widthPixels / scaleFactor;
if (widthInches >= 720) {
// 10" tablet resolutions
if (tempe_detail.toString().equals("")) {
temp_textview_temperature.setVisibility(View.GONE);
temp_textview_notfound.setVisibility(View.VISIBLE);
imageview_degree.setVisibility(View.GONE);
// temp_textview_notfound.setText(60);
chart.setVisibility(View.GONE);
} else {
temp_textview_notfound.setVisibility(View.GONE);
temp_textview_temperature.setVisibility(View.VISIBLE);
temp_textview_temperature.setText(tempe_detail);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// Do some stuff
temp_textview_temperature.setTextSize(70);
imageview_degree.getLayoutParams().height = 30;
imageview_degree.getLayoutParams().width = 30;
} else {
temp_textview_temperature.setTextSize(180);
imageview_degree.getLayoutParams().height = 50;
imageview_degree.getLayoutParams().width = 50;
}
imageview_degree.setVisibility(View.VISIBLE);
// temp_textview_temperature.setLayoutParams(llp);
chart.setVisibility(View.VISIBLE);
charDeclaration();
}
if (temp_textview_temperature.getText().toString()
.matches("[0-9.]*")) {
temp_textview_temperature.setPadding(0, 0, 0, 0);
} else if (temp_textview_temperature.getText().length() == 3) {
temp_textview_temperature.setPadding(20, 0, 0, 0);
} else {
temp_textview_temperature.setPadding(0, 0, 0, 0);
}
} else if (widthInches >= 600) {
// 7" tablet resolutions
if (tempe_detail.toString().equals("")) {
temp_textview_temperature.setVisibility(View.GONE);
temp_textview_notfound.setVisibility(View.VISIBLE);
imageview_degree.setVisibility(View.GONE);
chart.setVisibility(View.GONE);
} else {
temp_textview_notfound.setVisibility(View.GONE);
temp_textview_temperature.setVisibility(View.VISIBLE);
temp_textview_temperature.setText(tempe_detail);
temp_textview_temperature.setTextSize(140);
imageview_degree.setVisibility(View.VISIBLE);
// temp_textview_temperature.setLayoutParams(llp);
chart.setVisibility(View.VISIBLE);
charDeclaration();
}
if (temp_textview_temperature.getText().toString()
.matches("[0-9.]*")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
if (temp_textview_temperature.getText().length() == 3) {
temp_textview_temperature.setPadding(0, 0, 0, 0);
}
}
else {
temp_textview_temperature.setPadding(0, 0, 0, 0);
}
}
// }
}
}
use myChart.repaint(); to redraw your chart after date has been changed , if repaint doesn't work so before repainting the chart try using removeAllViews() to chart's parent layout.
chartlayout.removeAllViews();

aChartEngine: getting coordinates of tallest bar in the graph(Bar chart)

We are using AChart engine to draw bar graph. As per design requirement have to place an image on top of the tallest bar in the graph. We know the index of largest value in the XY series. Is there any method to find the coordinates of the tallest bar to position the image? Below is the helper class we are using to generate the bar graph. When user taps on the bar we have to place an image on top of the bar.
Issues :
Not able to get the click event correctly
How to position the image on top of the bar
public class BarGraphHelper {
private Context mContext;
private BarGraph mBarGraph;
private DisplayMetrics mMetrics;
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer renderer;
private View barChartView = null;
private BarChart chart;
public BarGraphHelper(Context context, BarGraph barGraph){
mContext = context;
mBarGraph = barGraph;
init();
}
private void init() {
renderer = new XYMultipleSeriesRenderer();
mDataset = new XYMultipleSeriesDataset();
mMetrics = mContext.getResources().getDisplayMetrics();
}
public View getBarGraphView(){
if(renderer == null){
return null;
}
getBarGraphDataset();
renderer = getBarRenderer();
setBarGraphSettings();
chart = new BarChart(mDataset, renderer, Type.DEFAULT);
barChartView = new GraphicalView(mContext, chart);
barChartView.setOnClickListener(onBarClick);
return barChartView;
}
private void setBarGraphSettings() {
if(renderer != null){
renderer.setXAxisMin(0.5);
renderer.setYAxisMin(0);
renderer.setYAxisMax(110);
renderer.setXLabelsColor(Color.WHITE);
renderer.setYLabelsColor(0, Color.WHITE);
renderer.setXTitle("mins");
renderer.setYTitle("Tweets");
renderer.setShowAxes(true);
renderer.setYLabelsAlign(Align.RIGHT);
renderer.setBarSpacing(0.2);
renderer.setBarWidth(15);
renderer.setShowGrid(false);
renderer.setYLabels(0);
renderer.setXLabels(0); // sets the number of integer labels to appear
int margin[] = renderer.getMargins();
renderer.setMargins(new int[] { (int)convertDiptoPixel(margin[0]), (int)convertDiptoPixel(margin[1]), (int)convertDiptoPixel(margin[2]), (int)convertDiptoPixel(margin[3]) });
renderer.setMarginsColor(Color.argb(0x00, 0xff, 0x00, 0x00));
renderer.setLabelsColor(Color.WHITE);
renderer.setAxisTitleTextSize(convertDiptoPixel(renderer.getAxisTitleTextSize()));
renderer.setShowLegend(false);
renderer.setLabelsTextSize(convertDiptoPixel(renderer.getLabelsTextSize()));
renderer.setZoomButtonsVisible(false);
renderer.setPanEnabled(true, true);
renderer.setZoomEnabled(false, false);
renderer.setClickEnabled(true);
renderer.setSelectableBuffer(10);
}
}
private void getBarGraphDataset() {
if(mBarGraph != null){
CategorySeries positiveSeries = new CategorySeries("Positive");
ArrayList<Sentiment> sentimentList = mBarGraph.getSentimentList();
if(sentimentList != null && !sentimentList.isEmpty()){
Sentiment sentiment = null;
for(int i=0; i< sentimentList.size(); i++){
sentiment = sentimentList.get(i);
positiveSeries.add(sentiment.getTotalTweetCount());
}
mDataset.addSeries(positiveSeries.toXYSeries());
}
}
}
public XYMultipleSeriesRenderer getBarRenderer() {
XYSeriesRenderer seriesRenderer = new XYSeriesRenderer();
seriesRenderer.setColor(Color.parseColor("#5FB356"));
seriesRenderer.setDisplayChartValues(true);
renderer.addSeriesRenderer(seriesRenderer);
return renderer;
}
private float convertDiptoPixel(float pixel){
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, pixel, mMetrics);
}
OnClickListener onBarClick = new OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = ((GraphicalView) barChartView).getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(mContext, "No chart element was clicked", Toast.LENGTH_SHORT)
.show();
} else {
double[] screenPoint = chart.toScreenPoint(new double[] {
seriesSelection.getXValue(),seriesSelection.getValue() },0);
Toast toast = Toast.makeText(
mContext,
"Chart element in series index " + seriesSelection.getSeriesIndex()
+ " data point index " + seriesSelection.getPointIndex() + " was clicked"
+ " closest point value X=" + seriesSelection.getXValue() + ", Y=" + seriesSelection.getValue()
+ " clicked point value X=" + (int)screenPoint[0] + ", Y=" + (int)screenPoint[1], Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, (int)screenPoint[0],(int)screenPoint[1]);
toast.show();
}
}
};
}

sometimes line doesn't shows on the graph- a chartengine

I have developed a application using a chart engine. and am using achartengine for drawing graphs.
I have drawn a graph using time chart. here dates are coming on x-axis and values on y axis. When the input dates are too long ie, if one date is jan-10 and 2nd date is apr 12 then the line between two points doesn't showing.
![enter image description here][there is another point on date jan 10 is there when we scroll we can see that but the line between point is not showing]1
this is code
public View getChartView(long startDate,long currentDate,int visibility)
{
String titles = "New tickets";
Date[]dateList = new Date[dates.length];
for(int i=0;i<dates.length;i++)
{
dateList[i]=convertDateFromString(dates[i]);
}
int[] colors = new int[] { Color.GREEN};
PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE};
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
setChartSettings(renderer, "Project work status", "Date", "Tickets",startDate,
currentDate,yMin,yMax, Color.GRAY, Color.LTGRAY);
float textSize=context.getResources().getDimension(R.dimen.text_title_medium);
CustomTimeChart chart2 = new CustomTimeChart(
buildDateDataset(titles, dateList, values), renderer,context,visibility,textSize);
// TimeChart chart = new TimeChart(buildDateDataset(titles, dateList, values), renderer);
chart2.setDateFormat("dd,MMM");
final GraphicalView graphView = new GraphicalView(context, chart2);
graphView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
SeriesSelection ss = graphView.getCurrentSeriesAndPoint();
if(ss!=null)
{
long clickedDateSeconds = (long) ss.getXValue();
Date clickedDate = new Date(clickedDateSeconds);
WeightTrackingActivity.dateCal.setTime(clickedDate);
WeightTrackingActivity.weight = ss.getValue();
try {
clickedDate=formatter.parse(clickedDate.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(clickedDate.before(Funcs.getCurrentDateInDate()))
WeightTrackingActivity.btnRecordWeight.setText("Update weight");
else
WeightTrackingActivity.btnRecordWeight.setText(WeightTrackingActivity.weightBtnText);
}
else
{
WeightTrackingActivity.btnRecordWeight.setText(WeightTrackingActivity.weightBtnText);
WeightTrackingActivity.dateCal.setTime(new Date());
}
}
});
return graphView;
}
protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle,
String yTitle, double startDate, double currentDate, double yMin, double yMax, int axesColor,
int labelsColor) {
// renderer.setAxesColor(axesColor);
renderer.setApplyBackgroundColor(true);
renderer.setBackgroundColor(Color.WHITE);
renderer.setShowGrid(true);
renderer.setGridColor(Color.LTGRAY);
renderer.setShowLegend(false);
renderer.setMarginsColor(Color.WHITE);
// renderer.setPanEnabled(true, true);
renderer.setClickEnabled(true);
// renderer.setPanLimits(new double[]{yMin,yMax});
renderer.setZoomEnabled(true, false);
renderer.setLabelsTextSize(context.getResources().getDimension(R.dimen.text_title_medium));
renderer.setPointSize(5f);
renderer.setXAxisMin(startDate);
renderer.setXAxisMax(currentDate);
renderer.setXLabelsColor(Color.BLACK);
renderer.setXLabels(5);
renderer.setXLabelsPadding(2);
renderer.setYAxisMin(yMin);
renderer.setYAxisMax(yMax);
renderer.setYLabels(6);
renderer.setYLabelsColor(0, Color.WHITE);
renderer.setYLabelsAlign(Align.RIGHT);
renderer.setYLabelsPadding(2);
}
protected XYMultipleSeriesDataset buildDateDataset(String titles,Date[] xValues,
double[] yValues) {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
TimeSeries series = new TimeSeries(titles);
sortingValues(xValues,yValues);
for (int k = 0; k < xValues.length; k++) {
series.add(xValues[k], yValues[k]);
}
dataset.addSeries(series);
return dataset;
}
private void sortingValues(Date[] xValues, double[] yValues) {
for(int i=0;i<xValues.length;i++)
{
for(int j=0;j<xValues.length-1;j++)
{
if(xValues[i].before(xValues[j]))
{
Date d = xValues[i];
xValues[i]=xValues[j];
xValues[j]=d;
Double x=yValues[i];
yValues[i]=yValues[j];
yValues[j]=x;
}
}
}
}
protected XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
setRenderer(renderer, colors, styles);
return renderer;
}
protected void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles) {
renderer.setMargins(new int[] { 20, 40, 15, 20 });
int length = colors.length;
for (int i = 0; i < length; i++) {
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(colors[i]);
r.setPointStyle(styles[i]);
r.setFillPoints(true);
r.setLineWidth(3);
r.setDisplayChartValues(true);
r.setChartValuesTextSize(context.getResources().getDimension(R.dimen.text_title_small));
r.setDisplayChartValuesDistance(2);
FillOutsideLine fillOutsideLine=new FillOutsideLine(FillOutsideLine.Type.BELOW);
fillOutsideLine.setColor(Color.parseColor("#A3E0FF"));
r.addFillOutsideLine(fillOutsideLine);
renderer.addSeriesRenderer(r);
}
}
private Date convertDateFromString(String date) {
Date dateConverted = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
dateConverted = df.parse(date);
} catch ( ParseException e ) {
}
return dateConverted;
}
you can turn hardware acceleration off
android:hardwareAccelerated="false"
to disable it for a particular view (This worked for me)
try:
View.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
I've added this after rendering the graph but it should work everywhere.

Android achartEngine how to highlight particular chart element

Hi i am using achartengine's pie-chart to represent my actual sales, now as my app starts one of the chart element in the piechart should get highlighted, like when we do the onclick on pie chart.
Below is the code for my piechart
final DefaultRenderer renderer = buildCategoryRenderer(colors);
renderer.setPanEnabled(false);// Disable User Interaction
renderer.setLabelsColor(Color.BLACK);
renderer.setShowLegend(true);
renderer.setLegendTextSize(20);
renderer.setInScroll(true);
renderer.setStartAngle(180);
renderer.setChartTitle("Sales By Market Segment- Month");
renderer.setLabelsTextSize(22);
final CategorySeries categorySeries = new CategorySeries("Sales");
categorySeries.add("Craft1", cursor.getInt(1));
categorySeries.add("product1", cursor.getInt(2) );
categorySeries.add("product2", cursor.getInt(3) );
categorySeries.add("product", cursor.getInt(4));
categorySeries.add("product1", cursor.getInt(5));
mChartView2=ChartFactory.getPieChartView(context, categorySeries,renderer);
parent.addView(mChartView2);
renderer.setClickEnabled(true);
mChartView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView2.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(getActivity(), "No chart element selected", Toast.LENGTH_SHORT)
.show();
}else {
for (int i = 0; i < categorySeries.getItemCount(); i++) {
renderer.getSeriesRendererAt(i).setHighlighted(i == seriesSelection.getPointIndex());
}
mChartView2.repaint();
Toast.makeText(
getActivity(),
"Chart data point index " + seriesSelection.getPointIndex() + " selected"
+ " point value=" + seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});
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;
}
products are getting highlighted when clicking but I want to highlight one product, when app starts.
Found the solution:
mChartView2=ChartFactory.getPieChartView(context, categorySeries,renderer);
parent.addView(mChartView2);
renderer.getSeriesRendererAt(0).setHighlighted(true);
mChartView2.repaint();

Android : Bar Chart and Pie Chart in Achartengine

i am drawing a bar chart and pie chart to represent the various application names in it using the achartengine library.
When i instantiate CategorySeries object it requires a series title as :
CategorySeries series = new CategorySeries("title") //IN BAR CHART
CategorySeries series = new CategorySeries("title") //IN PIE CHART
Unlike Pie chart the applications name does not get inflated at the bottom of the bar chart
say, in case of pie chart its as follows :
(1) application 1
(2) application 2
(3) application ... up to
(10) application 10.
But its not showing in case of bar char but instead its showing as :
(1) NUMBER OF APPLICATIONS ---->>> (This is the series title i had
passed in as the parameter while
instantiating the object of CategorySeries)
PLEASE SUGGEST ME TO SHOW THE KEY OF BAR CHART ASWELL,I HAVE ATTACHED A CODE SNIPPET BELOW
if (c.getCount() > 0) {
if (! mPieChart) {
series = new CategorySeries("NUMBER OF APPLICATIONS");
getActivity().startManagingCursor(c);
c.moveToPosition(-1);
//series.clear();
while (c.moveToNext()) {
recievedBytes = c.getLong(ApplicationDataCounterDao.CONTENT_RECEIVED_COLUMN);
sentBytes = c.getLong(ApplicationDataCounterDao.CONTENT_SENT_COLUMN);
totalBytes = (recievedBytes + sentBytes) / (1024 * 1024);
if (totalBytes > 0) {
applicationInfo
.add(new ApplicationDataUsage(
c.getString(ApplicationDataCounterDao.CONTENT_APPLICATION_NAME_COLUMN),
Double.toString(totalBytes)));
}
}
int size = applicationInfo.size();
for (int i = 0; i < size; ++i) {
Log.v("BAR CHART", "data added are " + applicationInfo.get(i).mApplicationName);
double value = Double.parseDouble(applicationInfo
.get(i).mDataUsage);
series.add("BAR", value);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series.toXYSeries());
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setDisplayChartValues(true);
renderer.setChartValuesSpacing((float) 0.5);
renderer.setColor(Color.CYAN);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
mRenderer.setBarSpacing(0.5);
mRenderer.getBarSpacing();
mRenderer.setXTitle("Application Number");
mRenderer.setYTitle("Data Usage");
mRenderer.setAxesColor(Color.GREEN);
mRenderer.setZoomButtonsVisible(true);
mRenderer.setInScroll(true);
mRenderer.setLabelsColor(Color.RED);
mRenderer.addSeriesRenderer(renderer);
if (mChartViewBar == null) {
Log.v(LOG_TAG, "chart view is null");
mChartViewBar = ChartFactory
.getBarChartView(getActivity(), dataset,
mRenderer, Type.DEFAULT);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartViewBar
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartViewBar
.getCurrentSeriesAndPoint();
CategorySeries series22 =new CategorySeries("333");
mChartViewBar.repaint();
if (seriesSelection == null) {
Toast.makeText(
getActivity(),
"No chart element was clicked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
getActivity(),
"APPLICATION NAME : "
+ series22.getTitle()
+ 1
+ " was clicked"
+ " DATA USAGE : "
+ seriesSelection
.getXValue(),
Toast.LENGTH_SHORT).show();
}
}
});
mChartLayout.removeAllViews();
mChartLayout.addView(mChartViewBar, new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
mChartLayout.removeAllViews();
mChartLayout.addView(mChartViewBar, new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mChartViewBar.repaint();
}
} else if (mPieChart) {
CategorySeries seriesPie = new CategorySeries("Pie Graph");
getActivity().startManagingCursor(c);
c.moveToPosition(-1);
while (c.moveToNext()) {
long recievedBytes = c .getLong(ApplicationDataCounterDao.CONTENT_RECEIVED_COLUMN);
Long sentBytes = c.getLong(ApplicationDataCounterDao.CONTENT_SENT_COLUMN);
totalBytes = (recievedBytes + sentBytes)
/ (1024 * 1024);
if (totalBytes > 0) {
applicationInfo
.add(new ApplicationDataUsage(
c.getString(ApplicationDataCounterDao.CONTENT_APPLICATION_NAME_COLUMN),
Double.toString(totalBytes)));
}
}
int size = applicationInfo.size();
for (ApplicationDataUsage data_value : applicationInfo) {
Log.v("PIE CHART", "data added are " + data_value.mApplicationName);
double dataUsage = Double
.parseDouble(data_value.mDataUsage);
seriesPie.add(data_value.mApplicationName, dataUsage);
}
for (int i = 0; i < size; ++i) {
prepareColors();
}
DefaultRenderer renderer = new DefaultRenderer();
for (int fillColor : colorList) {
// Log.d("1111111111",
// "FILL COLOUR TILL SIZE OF COLORLIST");
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(fillColor);
renderer.addSeriesRenderer(r);
}
renderer.setInScroll(true);
renderer.setChartTitle("APPLICATION WISE PIE CHART");
renderer.setChartTitleTextSize(20);
renderer.setApplyBackgroundColor(true);
renderer.setBackgroundColor(Color.BLACK);
renderer.setZoomButtonsVisible(true);
if (mChartViewPie == null) {
Log.v(LOG_TAG, "chat view is null");
// series.clear();
mChartViewPie = ChartFactory.getPieChartView(
getActivity(), seriesPie, renderer);
renderer.setClickEnabled(true);
renderer.setSelectableBuffer(10);
mChartViewPie
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartViewPie
.getCurrentSeriesAndPoint();
mChartViewPie.repaint();
if (seriesSelection == null) {
ToastHelper.showToastMessage(
"No item was Clicked",
getActivity());
} else {
ToastHelper.showToastMessage(
"Application number "
+ seriesSelection
.getPointIndex()
+ " was clicked and it's Data Usage is "
+ seriesSelection
.getValue(),
getActivity());
}
}
});
/*if (mChartViewBar != null) {
mChartLayout.removeView(mChartViewBar);
}
if (mChartViewPie != null) {
mChartLayout.removeView(mChartViewPie);
}*/
mChartLayout.addView(mChartViewPie, new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
/* if (mChartViewBar != null) {
mChartLayout.removeView(mChartViewBar);
}
if (mChartViewPie != null) {
mChartLayout.removeView(mChartViewPie);
}*/
mChartLayout.removeAllViews();
mChartLayout.addView(mChartViewPie, new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mChartViewPie.repaint();
}
}
You are confusing the legend with the X axis labels. The BarChart is an XYChart which means it is getting both legend and x axis labels. The PieChart is not an XYChart, so it is not getting X axis and Y axis.
The series titles go to the legend, as you mentioned.
In the X axis the series values indexes go by default. However, you can hide the default labels and add your own custom ones:
renderer.setXLabels(0);
renderer.addXTextLabel(1, "label);
renderer.addXTextLabel(2, "label);
...

Categories

Resources