Android ArrayAdapter Indexout of bounds exception
I'm using Android ArrayAdapter in my code, sometimes i see this error cropping up
java.lang.ArrayIndexOutOfBoundsException: index=-1 length=12
at java.util.ArrayList.get(ArrayList.java:310)
at com.sample.search.AutoCompleteAdapter.getItem(AutoCompleteAdapter.java:29)
Why would the index ever be -1?
I populate the ArrayAdapter using
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint != null) {
// A class that queries a web API, parses the data and returns an ArrayList<Symbol>
SymbolLookUp symLookUp = SymbolLookUp.getInstance();
try {
mData = symLookUp.getMatches(getContext(),constraint.toString());
}
catch(Exception e) {}
// Now assign the values and count to the FilterResults object
filterResults.values = mData;
filterResults.count = mData.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence contraint, FilterResults results) {
if(results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
And my getItem method is simply
@Override
public String getItem(int index) { 开发者_如何学Go
return mData.get(index).getSuggestedText();
}
@Override
public String getItem(int index) {
if(mData != null && mData.get(index) != null) {
return mData.get(index).getSuggestedText();
}
}
EDIT
You have not put your All code so i can not exactly say that you may face problem in mData.get(index) or not ..
But if you face problem of mData.get(index) is index out of bound exception then try below code
@Override
public String getItem(int index) {
if(mData != null && mData.size() >= index) {
return mData.get(index).getSuggestedText();
}
}
精彩评论