Make a chart from database MySQL in Android

I want to make a chart in Android based on the data I got from my database MySQL using JSON code, here's my code :

package android.bloodglucose.doctor;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.tools.PanListener;
import org.achartengine.tools.ZoomEvent;
import org.achartengine.tools.ZoomListener;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.bloodglucose.doctor.R;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ChartBuilder extends Activity {
  public static final String TYPE = "type";

  private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();

  private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();

  private XYSeries mCurrentSeries;

  private XYSeriesRenderer mCurrentRenderer;

  private String mDateFormat;

  private GraphicalView mChartView;

  private String textResult;

  private ArrayList<String> ids = new ArrayList<String>();
  private ArrayList<String> result = new ArrayList<String>();


  //private Button sendImage;

  InputStream is;

  String imageFilePath;

  private int index=1;

  @Override
  protected void onRestoreInstanceState(Bundle savedState) {
    super.onRestoreInstanceState(savedState);    
    mDataset = (XYMultipleSeriesDataset) savedState.getSerializable("dataset");
    mRenderer = (XYMultipleSeriesRenderer) savedState.getSerializable("renderer");
    mCurrentSeries = (XYSeries) savedState.getSerializable("current_series");
    mCurrentRenderer = (XYSeriesRenderer) savedState.getSerializable("current_renderer");
    mDateFormat = savedState.getString("date_format");
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("dataset", mDataset);
    outState.putSerializable("renderer", mRenderer);
    outState.putSerializable("current_series", mCurrentSeries);
    outState.putSerializable("current_renderer", mCurrentRenderer);
    outState.putString("date_format", mDateFormat);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.xy_chart);
    Button save = (Button)findViewById(R.id.saveChart);

    mRenderer.setApplyBackgroundColor(true);
    //mRenderer.setBackgroundColor(Color.WHITE);
    mRenderer.setShowGrid(true);
    mRenderer.setAxisTitleTextSize(16);
    mRenderer.setChartTitleTextSize(20);
    mRenderer.setLabelsTextSize(15);
    mRenderer.setLegendTextSize(15);
    //mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
    mRenderer.setZoomButtonsVisible(true);
    mRenderer.setPointSize(10);

        XYSeries series = new XYSeries("Blood Sugar Increment (mg/dl)");
        mDataset.addSeries(series);
        mCurrentSeries = series;
        XYSeriesRenderer renderer = new XYSeriesRenderer();
        mRenderer.addSeriesRenderer(renderer);
        renderer.setPointStyle(PointStyle.CIRCLE);
        renderer.setFillPoints(true);
        mCurrentRenderer = renderer;



       cek();
             }

  @Override
  protected void onResume() {
    super.onResume();
    if (mChartView == null) {
      LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
      mChartView = ChartFactory.getLineChartView(this, mDataset, mRenderer);
      mRenderer.setClickEnabled(true);
      mRenderer.setSelectableBuffer(100);
      mChartView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
          double[] xy = mChartView.toRealPoint(0);
          if (seriesSelection == null) {
            Toast.makeText(ChartBuilder.this, "No chart element was clicked", Toast.LENGTH_SHORT)
                .show();
          } else {
            Toast.makeText(
                ChartBuilder.this,
                "Your blood glucose level at this point is = " + (float) xy[1] + "mg/dl, where the normal level of blood glucose is < 140 mg/dl, " + textResult, Toast.LENGTH_SHORT).show();
          }
        }
      });
      mChartView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
          SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
          if (seriesSelection == null) {
            Toast.makeText(ChartBuilder.this, "No chart element was long pressed",
                Toast.LENGTH_SHORT);
            return false; // no chart element was long pressed, so let something
            // else handle the event
          } else {
            Toast.makeText(ChartBuilder.this, "Chart element in series index "
                + seriesSelection.getSeriesIndex() + " data point index "
                + seriesSelection.getPointIndex() + " was long pressed", Toast.LENGTH_SHORT);
            return true; // the element was long pressed - the event has been
            // handled
          }
        }
      });
      mChartView.addZoomListener(new ZoomListener() {
        public void zoomApplied(ZoomEvent e) {
          String type = "out";
          if (e.isZoomIn()) {
            type = "in";
          }
          System.out.println("Zoom " + type + " rate " + e.getZoomRate());
        }

        public void zoomReset() {
          System.out.println("Reset");
        }
      }, true, true);
      mChartView.addPanListener(new PanListener() {
        public void panApplied() {
          System.out.println("New X range=[" + mRenderer.getXAxisMin() + ", " + mRenderer.getXAxisMax()
              + "], Y range=[" + mRenderer.getYAxisMax() + ", " + mRenderer.getYAxisMax() + "]");
        }
      });
      layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
          LayoutParams.FILL_PARENT));
    } else {
      mChartView.repaint();
    }
  }



  public void cek(){

      String url_select = "http://10.0.2.2/BloodGlucose/selectUserChart.php";

      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url_select);

      //parameter
      String username = getIntent().getStringExtra("uname");
      ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
      param.add(new BasicNameValuePair("username", username));
      try {
         //add parameter
          httpPost.setEntity(new UrlEncodedFormEntity(param));

        HttpResponse httpRespose = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpRespose.getEntity();

        //read content
        InputStream in = httpEntity.getContent();
        BufferedReader read = new BufferedReader(new InputStreamReader(in));

        String content = "";
        String line = "";

        while((line = read.readLine())!=null){
           content += line;
        }

        Log.d("ADBUG", "content: "+content);


        //json
        if(!content.equals("null")){

           try {
              JSONArray jArr = new JSONArray(content);
              for(int i=0;i<jArr.length();i++){
                 JSONObject jObj = jArr.getJSONObject(i);

                 String a = jObj.getString("_id");
                 String b = jObj.getString("result");


                 ids.add(a.toString());
                 result.add(b.toString());


                 Double x,y;

                         x = Double.parseDouble(a.toString());
                         y = Double.parseDouble(b.toString());
                         mCurrentSeries.add(x, y);


              }

           } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           }

        }else{
           Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
        }

     } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
     } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
     }
  }

}

The problem is, the chart is empty, anyone can help me?

my databases
_id | result|
 1  | 180   |
 2  | 200   |
 3  | 145   |

This is my php code : selectUserChart.php

<?php
   include_once("koneksi.php");   

   $username = $_REQUEST['username']; 

   $sqlString = "SELECT * FROM login WHERE username_user = '$username'";

   $rs = mysql_query($sqlString);

   if($rs){
      while($objRs = mysql_fetch_assoc($rs)){
         $output[] = $objRs;
      }

      echo json_encode($output);
   }
   mysql_close();
?>

Answers


The only problem I saw in this code was related to your web service that returns the data. I commented that out as I cannot access it and added hardcoded data and the chart is displaying fine.

To see it yourself, please add the method below and call it instead of calling cek().

private void addData() {
  mCurrentSeries.add(0, 1);
  mCurrentSeries.add(1, 2);
  mCurrentSeries.add(2, 1);
  mCurrentSeries.add(3, 2);
}

Need Your Help

CommaSeparatedIntegerField Implementation

django django-models

Why is the Django Model class CommaSeparatedIntegerField implemented as text in MySQL as opposed to what it is: a list of integers? That seems like the most inefficient thing possible!

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.