我有一个listView,它是从包含22个项目的数据库中填充的。当我将数据库中的项目绑定到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;
}
答案 0 :(得分:2)
您正在尝试直接从列表视图元素中获取数据,这绝不是一个好主意。您获得空值因为屏幕上实际上只有7个项目。当您滚动时,七个项目会重新排列,其数据会发生变化,以至于它似乎在滚动,保持资源意识。列表视图应仅视为查看目的。如果您需要数据,请通过位置或ID或其他方式参考数据源,在这种情况下是您的arraylist。
答案 1 :(得分: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();
}
});