I have a problem that I can’t solve.
When I add items to a my database, I try to populate my listView and remove any item that equals " ", which are 3 blank spaces, from the listView, and NOT from the database just so that the users can’t see the empty rows. The method load() is called to do so. I keep getting a nullPointerException. It seems to find the item (I tested it with a System.out.println()) but when the remove method is called it crashes.
private void load() {
Cursor c=helper.getById(taskId);
c.moveToFirst();
String[] temp = getArray(helper.getPart(c));
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, temp);
lv.setAdapter(arrayAdapter);
int count = arrayAdapter.getCount();
for (int i = 0; i < count; i++) {
if (arrayAdapter.getItem(i).equals(" ")) {
arrayAdapter.remove(arrayAdapter.getItem(i));
}
}
arrayAdapter.notifyDataSetChanged();
c.close();
}
Well it happens because the list is shrinking when you do a remove in your loop.
Let’s say the size is 10 (so index 0 – 9) in the beginning, then when you remove the first item which matches your condition, the real size its going back to 9, but in your loop you still have “i < 10” when you try to access the index i = 9 then you have a
NullPointer Exception.Try the following:
Note that I replaced your
countvariable withgetCount()inside the loop. When you do it like this you should never have theNullPointer Exception.