java.lang.Исключение IndexOutOfBoundsException во время фильтрации адаптера

#java #android #filtering #android-arrayadapter

#java #Android #фильтрация #android-arrayadapter

Вопрос:

Предполагается, что эта часть кода фильтрует объекты в адаптере и удаляет или добавляет объекты в listview в зависимости от ввода пользователя. Однако, когда я пытаюсь ввести любую букву, я получаю сообщение об ошибке: java.lang.IndexOutOfBoundsException: недопустимый индекс 5, размер 5 или аналогичный в зависимости от ввода в EditText. Я не понимаю, что вызывает это.

Вот код:

 import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import nick.miros.BudgetControl.budgetcontrol.app.Currency;
import nick.miros.BudgetControl.budgetcontrol.app.R;

public class CurrencyAdapter extends ArrayAdapter<Currency> {
    private final Context context;
    private List<Currency> currencies;
    private CurrencyFilter currencyFilter;

    public CurrencyAdapter(Context context, List<Currency> currencies) {
        super(context, R.layout.list_currency, currencies);
        this.context = context;
        this.currencies = currencies;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.list_currency, parent, false);

        TextView currencyName = (TextView) rowView.findViewById(R.id.currencyName);
        TextView currencySymbol = (TextView) rowView.findViewById(R.id.currencySymbol);

        currencyName.setText(currencies.get(position).getCurrencyName());
        currencySymbol.setText(currencies.get(position).getSymbol());

        return rowView;
    }

    @Override
    public Filter getFilter() {
        if (currencyFilter == null)
            currencyFilter = new CurrencyFilter();

        return currencyFilter;
    }


    private class CurrencyFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            // We implement here the filter logic
            if (constraint == null || constraint.length() == 0) {
                // No filter implemented we return all the list
                results.values = currencies;
                results.count = currencies.size();
            }
            else {
                // We perform filtering operation
                List<Currency> nCurrencyList = new ArrayList<Currency>();

                for (Currency c : currencies) {
                    if (c.getCurrencyName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
                        nCurrencyList.add(c);
                }

                results.values = nCurrencyList;
                results.count = nCurrencyList.size();

            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) {

            // Now we have to inform the adapter about the new list filtered
            if (results.count == 0)
                notifyDataSetInvalidated();
            else {
                currencies = (List<Currency>) results.values;
                notifyDataSetChanged();
            }
        }
    }
}
  

Вот результат, который я получаю:

 06-29 23:08:05.369  15570-15570/nick.miros.BudgetControl.budgetcontrol.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IndexOutOfBoundsException: Invalid index 5, size is 5
            at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
            at java.util.ArrayList.get(ArrayList.java:304)
            at nick.miros.BudgetControl.budgetcontrol.helper.CurrencyAdapter.getView(CurrencyAdapter.java:41)
            at android.widget.AbsListView.obtainView(AbsListView.java:2337)
            at android.widget.ListView.measureHeightOfChildren(ListView.java:1289)
            at android.widget.ListView.onMeasure(ListView.java:1201)
            at android.view.View.measure(View.java:15669)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4946)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1433)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:720)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:593)
            at android.view.View.measure(View.java:15669)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4946)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:326)
            at android.view.View.measure(View.java:15669)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:872)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:593)
            at android.view.View.measure(View.java:15669)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4946)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:326)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2214)
            at android.view.View.measure(View.java:15669)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2232)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1316)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1510)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1206)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5004)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
            at android.view.Choreographer.doCallbacks(Choreographer.java:579)
            at android.view.Choreographer.doFrame(Choreographer.java:548)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5340)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
            at dalvik.system.NativeStart.main(Native Method)
  

который указывает на эту строку:

 currencyName.setText(currencies.get(position).getCurrencyName());
  

Комментарии:

1. Хорошо, нашел это. Мне нужно было реализовать метод getCount() в моем пользовательском адаптере.