MP Chart Android не обновляет Chart после получения значения моментального снимка в реальном времени - PullRequest
0 голосов
/ 21 февраля 2019

Я работаю на графике объединения MP Android.Я передаю данные в режиме реального времени на график с помощью Firebase.И я успешно сделал, чтобы получить данные и передать в объединенную диаграмму.

Но проблема в том, что, когда firebase обновляется из какого-то другого источника данных, диаграмма не обновляется в соответствии со значениями (полученными в моментальном снимке данных).

Вместо того, чтобы чат двигался вперед, но данные не обновляются, как вы можете видеть здесь .

Я видел много решений, но они различаются в зависимости от требований и типа диаграммы.Как решить мою проблему с графиком?Было бы здорово помочь.

Вот мой код onDataChange () .Вызов onCreate

    ref.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    for (DataSnapshot ds : dataSnapshot.getChildren()) {

                        //get FLOW RATE
                        String rate = ds.child("flowRate").getValue(String.class);
                        //get TIMESTAMP
                        long timestamp = ds.child("timestamp").getValue(Long.class);



                         //add, got TIMESTAMP to xAxisData (list)
                        xAxisData.add(getDatafTimeStamp(timestamp));
                        //add, got FLOW RATE to flow_rate (list)
                        flow_rate.add(rate);

                         combinedChart.notifyDataSetChanged();
                         combinedChart.invalidate();
    }

drawCombinedChart(xAxisData, flow_rate, quantity, followed);

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    datafetched = false;

                }
            });

Вот моя drawCombinechart () функция, вызываемая каждый раз, когда данные обновляются в firebase

public void drawCombinedChart(List<String> axis, final List<String> rate) {

   //set chart's description, grid, shadow when chart is loaded
    combinedChart.setDescription("");
    combinedChart.setDrawGridBackground(false);
    combinedChart.setDrawBarShadow(false);
    combinedChart.setNoDataText("Loading.....");


    // draw bars behind lines
    combinedChart.setDrawOrder(new CombinedChart.DrawOrder[]{
            CombinedChart.DrawOrder.BAR, CombinedChart.DrawOrder.LINE, CombinedChart.DrawOrder.LINE
    });
    Legend l = combinedChart.getLegend();
    l.setWordWrapEnabled(true);


    // Setting X_Axis of combine chart
    XAxis xAxis = combinedChart.getXAxis();
    xAxis.setLabelsToSkip(0);

    // Setting X_Axis position in bottom of combine chart
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); // to set xAxis in Bottom

    //setting X_Axis only on right side
    combinedChart.getAxisRight().setDrawLabels(true);
    combinedChart.getAxisLeft().setDrawZeroLine(false);
    combinedChart.getAxisRight().setAxisMinValue(0);

    // Setting Y_Axis to left side of combine chart
    YAxis y = combinedChart.getAxisLeft();
    y.setAxisMinValue(0);
    y.setGranularity(1f);
    y.setGranularityEnabled(true);
    y.setAxisLineColor(Color.BLACK);
    y.setTextColor(Color.BLACK);
    y.setEnabled(true);
    y.setAxisLineColor(Color.BLACK);
    y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
    y.setDrawGridLines(false);
    y.setLabelCount(5, true);
    y.setDrawZeroLine(false);
    y.isForceLabelsEnabled();
    y.setDrawLabels(true);
    y.setDrawLimitLinesBehindData(true);
    y.setDrawGridLines(true);
    y.setDrawLimitLinesBehindData(true);
    y.setTextColor(Color.RED);
    y.setDrawZeroLine(true);


    //animate Y_axis to 5 seconds
    combinedChart.animateY(0);

    // Setting Y_Axis to right side of combine chart
    YAxis rightAxis = combinedChart.getAxisRight();
    rightAxis.setDrawGridLines(true);
    rightAxis.setLabelCount(5, true);
    rightAxis.setDrawZeroLine(false);
    rightAxis.isForceLabelsEnabled();
    rightAxis.setDrawLabels(true);
    rightAxis.setDrawLimitLinesBehindData(true);
    rightAxis.setDrawGridLines(true);
    rightAxis.setDrawLimitLinesBehindData(true);
    rightAxis.setTextColor(Color.RED);
    rightAxis.setDrawZeroLine(true);

    //hide background grid lines of chart
    combinedChart.getXAxis().setDrawGridLines(false);
    combinedChart.getAxisLeft().setDrawGridLines(false);
    combinedChart.getAxisRight().setDrawGridLines(false);

    data = new CombinedData(axis);

    //when data loaded show msg onto chart
    combinedChart.setNoDataText("Data loaded");

    //switch pressed
    flw_Rate_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            //if FlOW RATE button is on
            if (isChecked) {

                //change state of other switches
                lqd_followed_switch.setChecked(false);
                //change color of current switch when ON
                flow_rate_switch_txt.setTextColor(Color.parseColor("#536BB5"));

                //call function to generate area chart
                mlineData = generateLineData(rate);
                data.setData(mlineData);
                combinedChart.setData(data);

                // allow 4 values to be displayed at once on the x-axis, not more
                combinedChart.setVisibleXRangeMaximum(4);
                combinedChart.moveViewToX(4);
                //animate y axis to 2 sec
                combinedChart.animateY(0);
                combinedChart.invalidate();

            }
            //if FlOW RATE button is off
            else {
                //change text color of flow rate switch
                flow_rate_switch_txt.setTextColor(Color.BLACK);

                //remove all data sets of area chart when switch turned OFF
                boolean indicator = data.removeDataSet(lineData1.getDataSetByLabel("Flow Rate", true));
                //notify to combine chart that data set has removed
                combinedChart.notifyDataSetChanged();
                //clear relative chart
                combinedChart.clear();
                combinedChart.setNoDataText("No data");
                combinedChart.invalidate();
                combinedChart.animateX(500);
            }
        }

    });

И моя функция generateLineData () , которая вызывается при включении переключателя для генерации данных диаграммы

 private LineData generateLineData(List<String> arr) {

    LineData d = new LineData();

    ArrayList<Entry> entries = new ArrayList<Entry>();

    for (int index = 0; index < arr.size(); index++)
        entries.add(new Entry(Float.parseFloat(arr.get(index)), index));

    LineDataSet set = new LineDataSet(entries, "Flow Rate");

    //set highlight line color
    set.setColor(Color.parseColor("#536BB5"));
    set.setLineWidth(2.5f);
    //set data points color
    set.setCircleColor(Color.RED);
    //set color to area occupied by chart
    set.setFillColor(Color.parseColor("#536BB5"));
    set.setCircleRadius(4f);
    //draw chart lines in cubic shape
    set.setDrawCubic(true);

    //set area occupied by chart must be filled
    set.setDrawFilled(true);

    set.setDrawValues(false);

    set.setHighLightColor(Color.MAGENTA);
    set.setLabel("Flow rate");
    set.setAxisDependency(YAxis.AxisDependency.LEFT);


    d.addDataSet(set);
    lineData1 = d;

    return d;
}

Ответы [ 3 ]

0 голосов
/ 21 февраля 2019

Сохраняя состояние переключателя для включения, я получил график в режиме реального времени.

0 голосов
/ 07 марта 2019

Вы должны сообщить своей диаграмме, что набор данных обновлен, и вам нужно обновить диаграмму, для чего вам нужно добавить следующие строки:

    combinedChart.notifyDataSetChanged();
    combinedChart.setData(data);
    combinedChart.invalidate();
0 голосов
/ 21 февраля 2019

Когда значения обновляются, вам нужно установить значения в mpChart.а для обновления mpchat просто скрыть и увидеть mpChart.

...