问题
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?
回答1:
The problem is in your xml file.
android:name="@+id/price_chart"
should be
android:id="@+id/price_chart"
回答2:
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.
来源:https://stackoverflow.com/questions/6318903/addview-causes-nullpointerexception