Reputation: 2943
I have created my own adapter which extends BaseAdapter implements Filterable.
I am occasionally getting index out of bounds error, in getView method:
private ArrayList<ResultHolderData> originalData;
private ArrayList<ResultHolderData> arrayList;
private LayoutInflater inflater;
private ArrayList<ResultHolderData> suggestions;
public static class ResultHolderData {
public String symbol;
public String fullName;
public ResultHolderData(String a, String b) {
symbol=a;
fullName=b;
}
}
public static class ResultHolder {
public TextView symName;
public TextView symNameFull;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ResultHolder rh;
if(convertView==null) {
rh=new ResultHolder();
convertView=inflater.inflate(R.layout.two_line_dropdown_item, null);
rh.symName=(TextView) convertView.findViewById(R.id.autocompleteSym);
rh.symNameFull=(TextView) convertView.findViewById(R.id.autocompleteName);
convertView.setTag(rh);
} else {
rh=(ResultHolder) convertView.getTag();
}
//rh.symName.setTextColor(Color.GREEN);
/***THE BELLOW LINE THROWS THE ERROR***/
rh.symName.setText(arrayList.get(position).symbol);
rh.symNameFull.setText(arrayList.get(position).fullName);
//rh.symName.setText(arrayList.get(position));
return convertView;
}
The arrayList represents the filtered resultSet:
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,FilterResults results) {
if(results.count>0 && results!=null) {
arrayList=(ArrayList<ResultHolderData>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
The error occurs sometimes, when you have 2 items in dropdown suggestions and when typing another letter causes the dropdown to only suggest one item. Then it says: Invalid index 1, size is 1.
My opinion: It usually happens when i am typing in fast, so i assume that NotifyDataSetChanged is in progress, but the publishResults changes the content of the arrayList and this causes the error. But then again i would expect this to happen in more situations?
Also another error pops out: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.
Any thoughts?
Upvotes: 0
Views: 413
Reputation: 2943
The problem was this line in publishResults:
arrayList=(ArrayList<ResultHolderData>) results.values;
which just pointed arrayList to those results, instead i made a "shallow copy" and cleared the list before it:
arrayList.clear();
for(ResultHolderData tempRhd : (ArrayList<ResultHolderData>)results.values)
arrayList.add(tempRhd);
and problem solved!
Upvotes: 1