AChartEngine doesn't show graph from remote database

40 views Asked by At

I am new to AChartEngine. I'm trying to retrieve JSON data from a remote database and plug it in AchartEngine Bar Chart. I can successfully fetch data. However, I'm having difficulties to plug it into the graph. The chart is not getting my data. When I hardcode or put a random number, it shows on the chart but when I try to include data from database it shows a blank page. I'm posting my code. Any help would be appreciated. I'm trying to show date in "X" axis and amount in "Y" axis.

public class BarGraphActivity extends AppCompatActivity {

private GraphicalView mChart;
private TimeSeries transactionSeries;
private XYMultipleSeriesDataset dataset;
private XYSeriesRenderer transactionRenderer;
private XYMultipleSeriesRenderer multiRenderer;

//JSON node name
private static final String TAG_TYPE = "type";
private static final String TAG_AMOUNT = "amount";
private static final String TAG_CATEGORY = "category";
private static final String TAG_DESC = "desc";
private static final String TAG_DATE = "date";
private static final String TAG_SUCCESS = "success";
static final String FETCH_URL = "my_url";


String amount = null;
String desc = null;
String type = null;
String date = null;
String category = null;
ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bar_graph);

    //showTransaction();
    //settingup bar chart


    //start plotting chart
    new ChartTask().execute();
}

public void setupChart(){

    //creating an Timeseries for Transactions
    transactionSeries = new TimeSeries("Transactions");

    //creating a dataset to hold each series
    dataset = new XYMultipleSeriesDataset();
    //adding transactionseries to the dataset
    dataset.addSeries(transactionSeries);

    //Creating a XYMultipleSeriesRenderer to customize transaction series
    transactionRenderer = new XYSeriesRenderer();
    transactionRenderer.setColor(Color.GREEN);
    //transactionRenderer.setPointStyle(PointStyle.CIRCLE);
    transactionRenderer.setFillPoints(true);
    transactionRenderer.setLineWidth(4);
    transactionRenderer.setDisplayChartValues(false);

    // Creating a XYMultipleSeriesRenderer to customize the whole chart
    multiRenderer = new XYMultipleSeriesRenderer();

    multiRenderer.setChartTitle("Transaction Trends");
    multiRenderer.setXTitle("Date");
    multiRenderer.setYTitle("Amount");
    //multiRenderer.setZoomButtonsVisible(true);

    multiRenderer.setXAxisMin(0);
    multiRenderer.setXAxisMax(10);

    multiRenderer.setYAxisMin(0);
    multiRenderer.setYAxisMax(10);

    multiRenderer.setBarSpacing(2);

    // Adding transactionRenderer to multipleRenderer
    // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
    // should be same
    multiRenderer.addSeriesRenderer(transactionRenderer);

    // Getting a reference to LinearLayout of the bar graph activity Layout
    LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);

    mChart = (GraphicalView) ChartFactory.getBarChartView(getBaseContext(), dataset, multiRenderer, BarChart.Type.DEFAULT);

    // Adding the Line Chart to the LinearLayout
    chartContainer.addView(mChart);
}

private class ChartTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(BarGraphActivity.this);
        pDialog.setMessage("Loading data. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override
    protected String doInBackground(String... String) {
        //int i = 0;
        //String[] amount = new String[];
        try {
            URL url = new URL(FETCH_URL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            int responsecode = urlConnection.getResponseCode();

            if(responsecode == HttpURLConnection.HTTP_OK){
                BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null){
                    sb.append(line);
                }
                br.close();
                return  sb.toString();
            }

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        pDialog.dismiss();


    try {
        //get JSONObject from JSONArray of String
        JSONArray result = new JSONArray(s);
        JSONObject jsonObject = null;
        String[] values = new String[2];
        //loop through the array and break the JSONObject into String
        for(int i = 0; i<result.length(); i++) {

            jsonObject = result.getJSONObject(i);
            amount = jsonObject.getString(TAG_AMOUNT);
            desc = jsonObject.getString(TAG_DESC);
            type = jsonObject.getString(TAG_TYPE);
            //getting date as string from database
            date = jsonObject.getString(TAG_DATE);
            //System.out.println(date);
            //write it in the db in a different format like Wednesday, July 12, 2016 12:00 PM
            SimpleDateFormat readFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm a");
            //SimpleDateFormat writeFormat = new SimpleDateFormat("MMMM dd, yyyy");

            //check it date string for null or empty string or else it will give Unparseable date: "" (at offset 0) error
            if(!date.equalsIgnoreCase("")) {
                try {
                    Date dt = readFormat.parse(date);  //parse the date string in the read format
                    //String dtStr = writeFormat.format(dt);

                    //dt = writeFormat.parse(dtStr);
                    //System.out.println(dt);
                    Log.d("Date: ", date);
                    double amt = Double.valueOf(amount.replace(",", ""));
                    //System.out.println(amt);
                    Log.d("Amount: ", String.valueOf(amt));

                    setupChart();
                    transactionSeries.add(dt.getTime(),amt);
                    mChart.repaint();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            else {
                return;
            }
        }

    }
    catch (JSONException e){
        e.printStackTrace();
    } //catch (ParseException e) {
      // e.printStackTrace();
  // }

    }

    // Plotting generated data in the graph
    /**@Override
    protected void onProgressUpdate(Object... values) {
        transactionSeries.add((Double) values[0], (Double) values[1]);
        mChart.repaint();
    }**/
}

Here is how the data looks when retrived

D/Date:: Wednesday, July 29, 2015 1:35 AM
D/Amount:: 221.06
D/Date:: Wednesday, November 25, 2015 3:27 PM
D/Amount:: 275.7

1

There are 1 answers

1
Sarath VK On

here the method "setupChart()", is calling before getting values from webservice via asynctask "new ChartTask().execute()". So, there is not getting values to plot the chart, or can say that values getting after ploting.

Solution: Please call the method "setupChart()" in asynctask onpostexecute.