在复选框监听器上显示/隐藏LineGraph / BarGraph,BarGraph无效。 MPAndroidChart Android

时间:2018-01-02 05:48:56

标签: android checkbox bar-chart mpandroidchart linechart

我正在使用MPANDROIDCHART库来显示图表, 在组合图表中,我显示折线图和条形图。我的要求是当Line复选框为true时它应该显示行,当Bar复选框为true时它应该显示条形图。 当我取消选中行复选框时,折线图应隐藏。 当取消选中栏时,复选框条形图应隐藏。

我的代码在Line的情况下工作但是在条形图的情况下,它不起作用我得到Nullpointer异常。

以下是我的代码。

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:orientation="vertical"
   android:layout_height="match_parent"
   tools:context="com.swytch.chartdemo.MainActivity">

   <LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">

    <CheckBox
        android:id="@+id/chechbToken"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="line" />

    <CheckBox
        android:id="@+id/chechbEnergy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bar" />

</LinearLayout>



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

</LinearLayout>

MainActivity.java

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private CombinedChart mChart;
    private final int itemcount = 12;
    private CheckBox chechmnb,chechabc;

    protected String[] mMonths = new String[] {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};

    private XAxis xAxis;

    private BarData barData;
    private LineData lineData;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        mChart = (CombinedChart) findViewById(R.id.chart1);

        checkBoxInitialiozation();
        chartInitialization();
        setChartDataBasic();
     }


     private void checkBoxInitialiozation() {

         chechabc = findViewById(R.id.chechbEnergy);
         chechmnb = findViewById(R.id.chechbToken);

         chechabc.setChecked(true);
         chechmnb.setChecked(true);

         chechabc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                 if (!b) {
                    if (!chechmnb.isChecked()) {
                        chechabc.setChecked(true);

                    } else {
                         chechabc.setChecked(false);
                      }

                 }
                 setChartData();

             }
           });
           chechmnb.setOnCheckedChangeListener(new 
  CompoundButton.OnCheckedChangeListener() {
             @Override
             public void onCheckedChanged(CompoundButton compoundButton, 
 boolean b) {
                 if (!b) {
                     if (!chechabc.isChecked()) {
                       chechmnb.setChecked(true);
                   } else {
                        chechmnb.setChecked(false);
                    }
                }
                setChartData();
            }
        });
    }
     protected float getRandom(float range, float startsfrom) {
         return (float) (Math.random() * range) + startsfrom;
     }

     private void chartInitialization() {

         mChart.getDescription().setEnabled(false);
         mChart.setBackgroundColor(Color.WHITE);
         mChart.setDrawGridBackground(false);
         mChart.setDrawBarShadow(false);
         mChart.setHighlightFullBarEnabled(false);

         // draw bars behind lines
         mChart.setDrawOrder(new CombinedChart.DrawOrder[]{
                 CombinedChart.DrawOrder.BAR,CombinedChart.DrawOrder.LINE
         });

         Legend l = mChart.getLegend();
         l.setWordWrapEnabled(true);
         l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
         l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
         l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
         l.setDrawInside(false);

         YAxis rightAxis = mChart.getAxisRight();
         rightAxis.setDrawGridLines(false);
         rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
         rightAxis.setEnabled(false);

         YAxis leftAxis = mChart.getAxisLeft();
         leftAxis.setDrawGridLines(false);
         leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

         xAxis = mChart.getXAxis();
         xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
         xAxis.setAxisMinimum(0f);
         xAxis.setGranularity(1f);

     }

     private LineData generateLineData(ArrayList<Entry> entries) {

         LineData d = new LineData();
         LineDataSet set = new LineDataSet(entries, "Token");

         set.setLineWidth(2.5f);

         set.setCircleRadius(3f);
         set.setCircleColor(getResources().getColor(R.color.colorAccent));
         set.setColors(getResources().getColor(R.color.colorAccent));
         set.setFillColor(getResources().getColor(R.color.colorPrimary));
       set.setValueTextColor(getResources().getColor(R.color.colorPrimary));
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set.setValueTextSize(10f);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
         //to draw value in side graph
        set.setDrawValues(false);
        d.addDataSet(set);

       return d;
    }

   private BarData generateBarData(ArrayList<BarEntry> entries) {

        BarDataSet set1 = new BarDataSet(entries, "Energy");
        set1.setColor(getResources().getColor(R.color.colorPrimary));

    set1.setValueTextColor(getResources().getColor(R.color.colorAccent));
    set1.setValueTextSize(10f);
    set1.setAxisDependency(YAxis.AxisDependency.LEFT);
    //to draw value inside graph
    set1.setDrawValues(false);

    float barWidth = 0.45f; // x2 dataset

    BarData d = new BarData(set1);
    d.setBarWidth(barWidth);

    return d;
   }
   private void setChartDataBasic() {

        ArrayList<BarEntry> entriesBarEntry = new ArrayList<BarEntry>();
        ArrayList<Entry> entriesLineEntry = new ArrayList<Entry>();


        entriesBarEntry.clear();
        entriesLineEntry.clear();

        for (int index = 0; index < itemcount; index++)
            entriesLineEntry.add(new Entry(index + 0.5f, getRandom(15, 5)));

         entriesBarEntry = getBarEnteries(entriesBarEntry);

         try {
             if (mMonths.length > 0) {
               xAxis.setValueFormatter(new IAxisValueFormatter() {
                   @Override
                    public String getFormattedValue(float value, AxisBase axis) {
                    return mMonths[(int) value % mMonths.length];
                }
            });

            barData = generateBarData(entriesBarEntry);
            lineData = generateLineData(entriesLineEntry);
            setChartData();
        } else {

            mChart.setData(null);
            mChart.notifyDataSetChanged();
            mChart.invalidate();
        }
    } catch (ArithmeticException e) {
        Log.d("MainActivity", "setChartData: " + e.getMessage());
    }
}


  public void setChartData() {

    CombinedData chartData = new CombinedData();
    if (chechabc.isChecked())
        chartData.setData(barData);
    if (chechmnb.isChecked())
        chartData.setData(lineData);
    xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
    mChart.setData(chartData);
    mChart.notifyDataSetChanged();
    mChart.invalidate();

  }


   private ArrayList<BarEntry> getBarEnteries(ArrayList<BarEntry> entries) {
    entries.add(new BarEntry(1, 20));
    entries.add(new BarEntry(2, 10));
    entries.add(new BarEntry(3, 80));
    entries.add(new BarEntry(4, 40));
    entries.add(new BarEntry(5, 20));
    entries.add(new BarEntry(6, 60));
    entries.add(new BarEntry(7, 22));
    entries.add(new BarEntry(8, 15));
    entries.add(new BarEntry(9, 45));
    return entries;
  }
 }

面临例外

 FATAL EXCEPTION: main
                                                                  Process: 
com.swytch.chartdemo, PID: 10510

java.lang.NullPointerException: Attempt to invoke virtual method 'int 
com.github.mikephil.charting.data.BarData.getDataSetCount()' on a null 
object reference
                                                                      at 
 com.github.mikephil.charting.renderer.BarChartRenderer
 .initBuffers(BarChartRenderer.java:61)
                                                                      at 
 com.github.mikephil.charting.renderer.CombinedChartRenderer
.initBuffers(CombinedChartRenderer.java:82)
                                                                      at 
 com.github.mikephil.charting.charts.BarLineChartBase
 .notifyDataSetChanged(BarLineChartBase.java:326)
                                                                      at 
  com.github.mikephil.charting.charts.Chart.setData(Chart.java:304)
                                                                      at 
  com.github.mikephil.charting.charts.CombinedChart
 .setData(CombinedChart.java:94)
                                                                      at 
   com.swytch.chartdemo.MainActivity
  .setChartData(MainActivity.java:240)
                                                                      at 
  com.swytch.chartdemo.MainActivity$1
  .onCheckedChanged(MainActivity.java:93)
                                                                      at 
  android.widget.CompoundButton.setChecked(CompoundButton.java:154)
                                                                      at 
  android.widget.CompoundButton.toggle(CompoundButton.java:113)
                                                                      at 
  android.widget.CompoundButton.performClick(CompoundButton.java:118)
                                                                      at 
  android.view.View$PerformClick.run(View.java:19884)
                                                                      at 
  android.os.Handler.handleCallback(Handler.java:739)
                                                                      at 
  android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at 
  android.os.Looper.loop(Looper.java:135)
                                                                      at 
  android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                      at 
  java.lang.reflect.Method.invoke(Native Method)
                                                                      at 
  java.lang.reflect.Method.invoke(Method.java:372)
                                                                      at 

  com.android.internal.os.ZygoteInit$MethodAndArgsCaller
  .run(ZygoteInit.java:905)
                                                                      at 
   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

OutputImage: -

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

将setChartData方法替换为:

public void setChartData()
{
    CombinedData chartData = new CombinedData();
    if(chechabc.isChecked() && chechmnb.isChecked())
    {
        chartData.setData(barData);
        chartData.setData(lineData);
    }
    else if (chechabc.isChecked())
    {
        LineData ld = new LineData();
        ld.clearValues();
        chartData.setData(ld);
        chartData.setData(barData);
    }

    else if (chechmnb.isChecked())
    {
        BarData bd = new BarData();
        bd.clearValues();
        chartData.setData(bd);
        chartData.setData(lineData);
    }

    xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
    mChart.setData(chartData);

    mChart.notifyDataSetChanged();
    mChart.invalidate();
}

With both datasets

Bar Data Only

Line Data Only

答案 1 :(得分:0)

尝试更改代码,如下所示。

public void setChartData() {

    CombinedData chartData = new CombinedData();
    boolean dataAvailable = false;
    if (chechabc.isChecked()) {
        chartData.setData(barData);
        dataAvailable = true;
    }
    if (chechmnb.isChecked()) {
        chartData.setData(lineData);
        dataAvailable = true;
    }
    if (dataAvailable) {
        mChart.setData(chartData);
    } else {
        mChart.setData(null);
    }
    xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
    mChart.notifyDataSetChanged();
    mChart.invalidate();
}