使用动态数据绘制LineChart?

时间:2017-05-19 05:15:35

标签: java android plot mpandroidchart

这是我第一次使用Graph并且它无法正常工作。我可以绘制静态折线图,但我无法使用动态数据绘制折线图。图表如何绘制动态数据?

fragment_dashboard

        <com.github.mikephil.charting.charts.LineChart
            android:id="@+id/chart1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

控制台

 public class Dashboard extends Fragment {

    ListView listViewNotice, listviewpendingbills;
    String Navigation_URL = "http://192.168.100.5:84/api/academics/getNotices";
    String Navigation_URL_BIlls = "http://192.168.100.5:84/Api/financeApi/getAllFees";
    String Navigation_URL_CHART = "http://192.168.100.5:84/api/academics/getSingleStudentsMarks";

    String access_token;
    String Notice, BillNumber, Status, AmountPaid, ReceiptIssueDate;
    String master_id;
    TextView pendingbills, NoNotice;
    BarChart lineChart;


    LineChart chart;


    private static final String TAG = "Test";


    ArrayList<Entry> entries = new ArrayList<>();
    LineDataSet set = new LineDataSet(entries, "Wow");
    LineData data = new LineData(set);
    ArrayList<Object> labels = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        // getActivity().setTitle("St. Xavier's High School");
        setHasOptionsMenu(true);

        listViewNotice = (ListView) view.findViewById(R.id.list_student_notice_dashboard);
        listviewpendingbills = (ListView) view.findViewById(R.id.student_dashboard_pendingbills);
        pendingbills = (TextView) view.findViewById(R.id.textpendingbills);
        NoNotice = (TextView) view.findViewById(R.id.textnoticedashboard);
        //  lineChart = (BarChart) view.findViewById(R.id.chart1);
        chart = (LineChart) view.findViewById(R.id.chart1);


        SessionManagement session = new SessionManagement(getContext());
        session.checkLogin();
        access_token = session.getAccesstToken();
        master_id = session.getMasterId();
        makeJsonObjectRequest();
        makeJsonObjectRequestBills();
        makeJsonObjectRequestGraph();
        return view;
    }
  private void makeJsonObjectRequestGraph() {

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String URL1 = Navigation_URL_CHART + "?StdID=" + master_id;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {


                            JSONArray jArray = new JSONArray(response);
                            for (int i = 0; i < jArray.length(); i++) {
                                JSONObject jsonObject = jArray.getJSONObject(i);
                                String Marks = jsonObject.getString("Marks");
                                String examDescription = jsonObject.getString("examDescription");

                                if (examDescription == "First Term") {

                                    entries.add(new BarEntry(Float.parseFloat(Marks), i));
                                }


                            }


                            chart.notifyDataSetChanged();
                            chart.invalidate();
                            set = new LineDataSet(entries, "Wow");
                            //data = new LineData(labels,set);
                            chart.setData(data);

                            setListViewHeightBasedOnChildren(listviewpendingbills);


                        } catch (JSONException e) {
                            Toast.makeText(getContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), error.toString(), LENGTH_LONG).show();
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }
/*
            @Override
            protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();

                map.put("id", master_id);
                map.put("accessID", accessID);
                map.put("currentUser", master_id);
                return map;

            } */
        };


        requestQueue.add(stringRequest);

    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.dashboard, menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do s.th.
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
}

JSON

[
  {
    "CLASSNO": "8",
    "CLASS_ID": 8,
    "CourseID": 1012,
    "Marks": 80,
    "Sno": 1,
    "StdID": 2,
    "TermID": 6014,
    "CourseName": "Math",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Oren Oneill"
  },
  {
    "CLASSNO": "8",
    "CLASS_ID": 8,
    "CourseID": 1013,
    "Marks": 80,
    "Sno": 2,
    "StdID": 2,
    "TermID": 6014,
    "CourseName": "Nepali",
    "Terminal_FM": 100,
    "Terminal_PM": 40,
    "UT_FM": 50,
    "UT_PM": 20,
    "examDescription": "First Term",
    "type": "Terminal",
    "NAME": "Oren Oneill"
  }
]
  

如何使用MPAndroidChart在Android中绘制动态数据?

1 个答案:

答案 0 :(得分:0)

将ArrayList条目,LineDataSet,LineData作为全局,在onCreate中初始化它,然后在for循环中添加以下代码

 if(examDescription.equals("First Term")){
 entries.add(new BarEntry(Marks, i));}

在for循环后执行此操作,

     chart.notifyDataSetChanged();
     chart.invalidate();
     set = new LineDataSet(entries, "Wow");
     data = new LineData(labels,set);
     chart.setData(data);