2012-10-15 43 views
2

這裏是我的getView()方法。充氣時我得到空指針異常。同樣的問題有很多答案。這用在一個片段中。但那不適合我。BaseAdapter中的LayoutInflater中的NullPointerException getView()方法

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    Context con = null; 
    View vi=convertView; 
    if(convertView==null){ 
      LayoutInflater inflater = (LayoutInflater)con.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      vi = inflater.inflate(R.layout.stores_listview_layout, null); 
    } 

    TextView tv = (TextView)vi.findViewById(R.id.store_name); 
    tv.setText(storeData.get(position).get("merchantName")); 

    return vi; 
} 

我在這裏做的錯誤是什麼?

更新:This Works!

  View vi=convertView; 
     Context c = null; 
     if(convertView==null){ 
     LayoutInflater inflater = getLayoutInflater(null); 
     vi = inflater.inflate(R.layout.stores_listview_layout, parent, false); 
     } 
+0

訪問layoutinflater ??? –

+1

上下文con永遠不會初始化 –

+1

而不是con.getApplicationContext(),請嘗試使用您的Activity的上下文。 –

回答

4
LayoutInflater inflater = getLayoutInflater(null); 
vi = inflater.inflate(R.layout.stores_listview_layout, parent, false); 
+0

這種方法是在一個片段 – intrepidkarthi

+0

你試試嗎? – mukesh

+0

是的。我嘗試過這個。沒有工作 – intrepidkarthi

1
con.getApplicationContext()... 

這裏是你的錯。 con尚未初始化,所以它是null。 你應該使用你的Activity作爲上下文。

+0

它在一個片段內 – intrepidkarthi

+0

然後你可以爲你的上下文調用getActivity()。 – nhaarman

0

這裏

Context con;///============> here 
View vi=convertView; 
if(convertView==null){ 
     LayoutInflater inflater = (LayoutInflater)con.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     vi = inflater.inflate(R.layout.stores_listview_layout, null); 
.... 

在此代碼未初始化變量上下文替換Context con;

Context con= getApplicationContext(); 

這裏。嘗試先初始化它。

+0

它在一個片段內 – intrepidkarthi

3

,而不用聲明Context con;,然後用它 - 這是指出了導致空指針異常,你可以簡單地使用convertView.getContext()

檢查文檔here


剛纔已經真正想過這個問題,並我的第一個想法是行不通的 - Doh!

因爲你的代碼片段裏,你可以在該行通過getActivity()

public View getView (int position, View convertView, ViewGroup parent){ 
    if(convertView == null){ 
     //you can access layout inflater by accessing hosting activity 
     convertView = getActivity().getLayoutInflater().inflate(R.layout.stores_listview_layout, parent, false); 
    } 
    TextView tv = (TextView)convertView.findViewById(R.id.store_name); 
    tv.setText(storeData.get(position).get("merchantName")); 
    return convertView; 
} 
+0

它在一個片段 – intrepidkarthi

+1

啊,稍微有點不同的調用到layoutinflater然後。編輯... –

相關問題