PhilJay / MPAndroidChart

A powerful 🚀 Android chart view / graph view library, supporting line- bar- pie- radar- bubble- and candlestick charts as well as scaling, panning and animations.
Other
37.53k stars 9.01k forks source link

App crashing (simple linechart null object) #2600

Open Aduci01 opened 7 years ago

Aduci01 commented 7 years ago

I get this error: Unable to start activity ComponentInfo{com.example.adam.polocoach/com.example.adam.polocoach.Graphicons}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.BarChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference -> My linechart is a null object but i can't figure out why...

My xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.adam.polocoach.Graphicons" android:id="@+id/rl">

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

My activity: LineChart lineChart;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_graphicons);

    //lineChart = (BarChart) findViewById(R.id.lineChart);
    lineChart = new LineChart(this);
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
    rl.addView(lineChart);

    ArrayList<Entry> barEntries = new ArrayList<>();
    barEntries.add(new Entry(10f, 0));
    barEntries.add(new Entry(15f, 1));
    barEntries.add(new Entry(30f, 2));
    LineDataSet lineDataset = new LineDataSet(barEntries, "asd");
    ArrayList<String> labels = new ArrayList<>();
    labels.add("1");
    labels.add("2");
    labels.add("3");

    LineData data = new LineData(lineDataset);
    lineChart.setData(data);
    lineChart.invalidate();
}

I've tried to add lineChart manually too. Pls help

GoneUp commented 7 years ago

Well, you have a BarChart and you are working with a linechart in your Java Code. Also the android:id is not matching. If you are you defining it in the xml file there is no need to create a new instance in code you just need to set the data.