I have a listView that is populated from a database wich has 22 items. All the items show up in the list when I bind the items from the database to my listView.
But here is the problem.. I can select only the top 7 items from the listView.
When I try to select the 8th – 22th item in the view I get a nullpointerException.
Does anyone know why and how I can fix this problem?
My code when selecting items in the list:
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();
}
});
Code when Binding the values to 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;
}
You’re trying to get data from the listview elements directly which is never a good idea. You’re getting nulls cause there really is only 7 items on the screen. When you scroll, the seven items are rearranged with their data changed so that it seems like it’s scrolling, keeps things resource conscious. Listviews should be seen as only for viewing purposes. If you need data, refer to the data source via position or Id or otherwise, in this case your arraylist.