2012-11-12 22 views
1

我有一個從數據庫填充的列表視圖,其中有22個項目。當我將數據庫中的項目綁定到listView時,所有項目都顯示在列表中。當我選擇列表下方的項目時,我的ListView得到了nullpointerException

但這裏是問題..我只能從listView中選擇前7項。 當我嘗試選擇視圖中的第8至第22項時,我得到一個nullpointerException。

有誰知道爲什麼以及如何解決這個問題?

我的代碼在列表中選擇項目時:

 listView.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { 
       //ListView lv = (ListView) arg0; 
       TextView tv = (TextView) ((ListView) findViewById(R.id.list_view)).getChildAt(arg2); 
       //error here \/ 
       if (tv == null) { 
        Log.v("TextView", "Null"); 
       } 

       String s = tv.getText().toString(); 
       _listViewPostion = arg2; 

       Toast.makeText(CustomerPick.this, "Du valde: " + s, arg2).show(); 
     } 
    }); 

代碼綁定值的ListView時:

public ArrayAdapter<Customer> BindValues(Context context){ 
    ArrayAdapter<Customer> adapter = null; 
    openDataBase(true); 

    try{ 

     List<Customer> list = new ArrayList<Customer>(); 
     Cursor cursor = getCustomers(); 

     if (cursor.moveToFirst()) 
     { 
      do 
      { 
       list.add(new Customer(cursor.getInt(0), cursor.getString(1))); 
      } 
      while (cursor.moveToNext()); 
     } 
     _db.close(); 
     Customer[] customers = (Customer []) list.toArray(new Customer[list.size()]); 
     Log.v("PO's",String.valueOf(customers.length)); 


     adapter = new ArrayAdapter<Customer>(context, android.R.layout.simple_list_item_single_choice, customers); 

     } 
     catch(Exception e) 
     { 
      Log.v("Error", e.toString()); 
     } 
     finally{ 
      close(); 
     } 
    return adapter; 
} 
+1

你爲什麼手動得到參考'TextView'在'onItemClick()'?只需使用'arg1'。 – Magicode

回答

2

你試圖從列表視圖元素直接這是從來沒有得到數據一個好主意。你會得到空值,因爲屏幕上只有7個項目。當您滾動時,這七個項目會重新排列,其數據會發生變化,看起來好像在滾動,從而使資源保持意識。列表視圖應被視爲僅用於查看目的。如果您需要數據,請參閱數據源通過位置或Id或其他方式,在這種情況下,您的數據列表。

+0

謝謝!這有助於:-) – NiklasHansen

1

參見:http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html

修改後的代碼:

listView.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
      long arg3) { 

      //arg1 -> The view within the AdapterView that was clicked (this will be a view provided by the adapter) 
      //arg0 -> The AdapterView where the click happened. 
      //arg2 -> The position of the view in the adapter. 
      //arg3 -> The row id of the item that was clicked. 

      TextView tv = (TextView) arg1.findViewById(R.id.list_view); 

      if (tv == null) { 
       Log.v("TextView", "Null"); 
      } 

      String s = tv.getText().toString(); 
      _listViewPostion = arg2; 

      Toast.makeText(CustomerPick.this, "Du valde: " + s, arg2).show(); 
    } 
}); 
相關問題