2011-06-11 95 views
0

美好的一天! 我正在實現aChartEngine在Android上繪製圖表,並面臨一個麻煩:當嘗試添加創建圖表視圖到佈局與addView方法時,我收到NullPointerException。addView cause NullPointerException

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(); 
    } 
} 

是什麼想法,有什麼可這個錯誤的原因是什麼?

+0

你已經證實,它是是導致NPE還是它的chart_price佈局? – Noel 2011-06-12 00:20:26

+0

我使用下面的代碼,它顯示chart_price不爲null。我的猜測是,錯誤會導致addView方法或chart_layout.xml的設置。 ::::::::::::::::: System.out.println(「在ADDVIEW之前」); \t \t System.out.println(chart_price == null); \t \t layout.addView(chart_price); – dimzul 2011-06-12 05:38:50

回答

3

問題出在你的xml文件中。

​​

應該

android:id="@+id/price_chart" 
+0

非常感謝您指出我的錯誤!現在它正常工作! – dimzul 2011-06-12 20:10:19

0

對XML文件進行任何更改,然後保存並再次運行。當我今天早些時候遇到類似的問題時爲我工作。

+0

我已經多次更改此文件,但沒有任何積極影響。即使試圖將RelativeLayout更改爲LinearLayout ...也沒有幫助。有什麼變化幫助你? – dimzul 2011-06-12 05:43:37

+0

諾埃爾已經發布了你的問題的答案,所以不要理我,因爲這不是你的問題。 – Fraggle 2011-06-12 12:16:29