1

我有一个从包含 22 个项目的数据库中填充的 listView。当我将数据库中的项目绑定到我的 listView 时,所有项目都会显示在列表中。

但这是问题所在。我只能从 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;
}
4

2 回答 2

2

您试图直接从 listview 元素中获取数据,这绝不是一个好主意。你得到空值是因为屏幕上真的只有 7 个项目。当您滚动时,这七个项目会重新排列,并更改它们的数据,使其看起来像是在滚动,从而保持资源意识。列表视图应被视为仅用于查看目的。如果您需要数据,请通过位置或 Id 或其他方式引用数据源,在本例中为您的数组列表。

于 2012-11-12T09:32:05.387 回答
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();
    }
});
于 2012-11-12T09:36:22.633 回答