2012-11-12 2 views
1

22 개 항목이있는 데이터베이스에서 채워지는 listView가 있습니다. 데이터베이스의 항목을 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(); 
     } 
    }); 

코드 :

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

왜 수동으로'onItemClick()'에서'TextView'에 대한 참조를 얻고있다 : http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html

코드 수정? 그냥'arg1'을 사용하십시오. – Magicode

답변

2

을 당신은 결코 직접 목록보기 요소에서 데이터를 가져 오기 위해 노력하고 좋은 아이디어. 정말 화면에 단 7 항목 때문에 당신은 nulls지고 있어요. 스크롤 할 때 데이터가 변경된 상태에서 7 개 항목이 다시 정렬되어 스크롤되는 것처럼 보일뿐 아니라 리소스를 의식적으로 유지합니다. 목록보기는보기 목적으로 만 보여야합니다. 데이터가 필요하면 위치 또는 ID 또는 다른 경우 (이 경우 arraylist) 데이터 소스 을 참조하십시오.

+0

감사합니다. 이것은 도움이 :-) – NiklasHansen

1

참조 :

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(); 
    } 
}); 
관련 문제