addView causes NullPointerException

旧城冷巷雨未停 提交于 2020-01-17 05:05:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!