Search code examples
javaandroidlistviewtextwatcher

Filtering ListView with TextWatcher gets IndexOutOfBoundsException


I have tried this Filter ListView with arrayadapter, and this Filter List links, to achieve an list filterable, but I keep getting this error:

Process: br.com.soutsapp.user.souts, PID: 315 java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at br.com.soutsapp.user.souts.userInterface.adapter.EstablishmentAdapter.getView(EstablishmentAdapter.java:54)

This error happen on my getView:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    br.com.soutsapp.user.souts.userInterface.viewHolder.Establishment viewHolder;
    View rowView = convertView;
    if(convertView == null){
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = layoutInflater.inflate(R.layout.establishment_row, null, true);

        viewHolder = new br.com.soutsapp.user.souts.userInterface.viewHolder.Establishment();
        viewHolder.ivIcon = (ImageView) rowView.findViewById(R.id.iv_icon);
        viewHolder.tvClosingTime = (TextView) rowView.findViewById(R.id.tv_closing_time);
        viewHolder.tvOpeningTime = (TextView) rowView.findViewById(R.id.tv_opening_time);
        viewHolder.tvDistance = (TextView) rowView.findViewById(R.id.tv_place_distance);
        viewHolder.tvName = (TextView) rowView.findViewById(R.id.tv_name);
        viewHolder.tvWorkingStatus = (TextView) rowView.findViewById(R.id.tv_working_status);
        viewHolder.tvType = (TextView) rowView.findViewById(R.id.tv_type);

        rowView.setTag(viewHolder);
    }
    else {
        viewHolder = (br.com.soutsapp.user.souts.userInterface.viewHolder.Establishment) convertView.getTag();
    }

    Establishment establishment = establishmentList.get(position); //Error here
    viewHolder.ivIcon.setImageDrawable(establishment.getIcon());
    viewHolder.tvClosingTime.setText(establishment.getClosingTime().toString("HH:mm"));
    viewHolder.tvOpeningTime.setText(establishment.getOpeningTime().toString("HH:mm"));
    viewHolder.tvName.setText(establishment.getName());
    viewHolder.tvType.setText(establishment.getType());

    viewHolder.tvWorkingStatus.setText(establishment.getWorkingStatusLabel());
    viewHolder.tvWorkingStatus.setTextColor(getColorWorkingStatusLabel(establishment.isWorkingStatus()));

    viewHolder.tvDistance.setText(formatDistance(establishment.getDistance()));

    rowView.setId((int)establishment.getId());
    return rowView;
}

And I couldn't figure out how to solve this, can you show me the way? Thanks!


Solution

  • Override getCount method and return your list size . Inside your adapter class .