AChartEngine不显示远程数据库中的图形

时间:2016-11-25 09:32:47

标签: android json asynchronous achartengine

我是AChartEngine的新手。我试图从远程数据库中检索JSON数据并将其插入AchartEngine条形图中。我可以成功获取数据。但是,我很难将其插入图表中。图表没有获取我的数据。当我硬编码或放一个随机数时,它会显示在图表上,但当我尝试从数据库中包含数据时,它会显示一个空白页面。我发布了我的代码。任何帮助,将不胜感激。我试图在" X"轴和数量在" Y"轴。

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();
    }**/
}

以下是重试后数据的显示方式

  

D /日期:: 2015年7月29日星期三上午1:35
  D / Amount :: 221.06
  d /日期::   2015年11月25日星期三下午3:27
  D / Amount :: 275.7

1 个答案:

答案 0 :(得分:0)

这里的方法&#34; setupChart()&#34;,在通过asynctask&#34; new ChartTask()。execute()&#34;从webservice获取值之前调用。因此,没有获得绘制图表的值,或者可以说在绘制后得到的值。

解决方案:请调用方法&#34; setupChart()&#34;在asynctask onpostexecute。