addView causes NullPointerException

2019-08-30 23:52发布

Good day! I'm implementing aChartEngine to draw charts on Android and have faced with a trouble: I receive NullPointerException when try to add created chart view to layout with addView method.

chart_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/charts_relative_layout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout
        android:name="@+id/price_chart"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
// other elements
</RelativeLayout>

Charts.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chart_layout);
     //other code
}


protected void onResume() {
    super.onResume();

    if (chart_price == null) { 
    LinearLayout layout = (LinearLayout) findViewById(R.id.price_chart);
    chart_price = ChartFactory.getLineChartView(this, buildDataset(getTitles(), dateArray, priceArray), getRenderrer(paramList.get(0).length, paramList.get(1).length, maxPrice));          
    layout.addView(chart_price);    // THIS LINE CAUSES NULLPOINTEREXCEPTION
    }
    else {
      chart_price.repaint();
    }
 }

Are any ideas, what can be the reason of this error?

2条回答
疯言疯语
2楼-- · 2019-08-31 00:25

The problem is in your xml file.

    android:name="@+id/price_chart"

should be

    android:id="@+id/price_chart"
查看更多
萌系小妹纸
3楼-- · 2019-08-31 00:41

Make any change to your XML file and then save and run it again. Worked for me when I had a problem earlier tonight that was similar.

查看更多
登录 后发表回答