如何使用MPAndroidChart每隔x秒重绘一次图表?

时间:2017-01-06 22:11:06

标签: android json android-fragments mpandroidchart

我有一个饼图(MPAndroidChart)通过Volley获取数据,我使用以下内容每3秒更新一次图表,但图表没有重新绘制。这都位于标签视图中显示的片段内。当我单击另一个选项卡并返回到该选项卡时,该图表仅刷新。当我在页面上时,它不会重绘自己。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.activity_device_current_report, container, false);

        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                new AttemptJson().execute();
            }
        }, 3000);
        return layout;
    }

我有一个内部类AttemptJson:

class AttemptJson extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... strings) {
            updateChart();
            return "";
        }
    }

这是我的updateChart方法,它抓取JSON文件并使用Volley存储它。

private void updateChart() {

        requestQueue = Volley.newRequestQueue(getContext());
        JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url,

                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray dataset = response.getJSONArray("dataset");
                            JSONArray time = response.getJSONArray("time");

                            JSONArray temp = dataset.getJSONObject(0).getJSONArray("data");
                            JSONArray humid = dataset.getJSONObject(1).getJSONArray("data");
                            for (int i = 0; i < temp.length(); i++) {
                                float temp_data = Float.parseFloat(temp.getJSONObject(i).getString("value"));
                                float time_data = Float.parseFloat(time.getJSONObject(i).getString("time"));

                                temperature.add(new Entry(time_data, temp_data));
                            }
                            float data = (float)(Float.parseFloat(humid.getJSONObject(humid.length()-1).getString("value")) + Math.random()*20 - 5);
                            if(humidity.size() != 0) humidity.clear();
                            humidity.add(new PieEntry(data));
                            humidity.add(new PieEntry(100 - data));

                            drawGraph();
                        } catch (JSONException e) {
                            Log.d("debug", "Object dataset is incorrect");
                            e.printStackTrace();
                        }
                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        requestQueue.add(req);
    }

在该方法中,我调用drawGraph()绘制实际图形:

private void drawGraph() {
        LineChart temperatureChart;
        PieChart humidityChart;

        LineDataSet lineDataSet1 = new LineDataSet(temperature, "temperature");
        lineDataSet1.setDrawCircles(false);
        lineDataSet1.setColor(Color.BLUE);
        lineDataSet1.setDrawValues(false);

        temperatureChart = (LineChart) getActivity().findViewById(R.id.curr_chart_temp);
        humidityChart = (PieChart) getActivity().findViewById(R.id.curr_chart_humid);

        temperatureChart.setData(new LineData(lineDataSet1));
        temperatureChart.getAxisLeft().setAxisMinimum(-50f);
        temperatureChart.getAxisLeft().setAxisMaximum(50f);
        temperatureChart.getAxisRight().setEnabled(false);
        temperatureChart.animateX(2000);
        temperatureChart.setVisibleXRangeMaximum(400);
        temperatureChart.invalidate();

        PieDataSet dataset = new PieDataSet(humidity,"Humidity");
        dataset.setColors(new int[]{Color.RED,Color.WHITE});
        PieData humidValue= new PieData(dataset);
        humidValue.setDrawValues(false);
        humidityChart.setData(humidValue);
        DecimalFormat df = new DecimalFormat("#.##");
        humidityChart.setCenterText( df.format(humidity.get(0).getValue()) + "%");
        humidityChart.setDrawCenterText(true);
        humidityChart.animateY(1000);

    }

1 个答案:

答案 0 :(得分:0)

使用findViewById重复获取View作为函数局部变量的句柄并不是Android中的正确方法。您当前的代码正在更新屏幕上显示的LineChart的单独实例。

而是制作LineChartPieChart类字段。

public class MyFragment extends Fragment {
    private final LineChart lineChart;
    private final PieChart pieChart;

    public View onCreateView() {  
        View layout = inflater.inflate(R.layout.activity_device_current_report, container, false);  
        lineChart = layout.findViewById(R.id.curr_chart_temp);
        pieChart = layout.findViewById(R.id.curr_chart_humid);
        //insert the rest of your onCreate() code
    }
}

然后在updateChart()中,您可以使用除LineChartPieChartfindViewById声明之外的其余代码。修改数据集后,请不要忘记调用notifyDatasetChanged()