0

In the classical version my adapter worked well. The app began to crash after I decided to add a button at the end of the list. I have ArrayIndexOutOfBoundsException in getItemId() and can't figured out how to fix it. The button implementation is found here

methods onCreateViewHolder(), onBindViewHolder() and class `ViewHolder don't contain anything remarkable, so i just pointed out that they are present.

adapter:

public class PersonAdapter
        extends RealmRecyclerViewAdapter<Person, RecyclerView.ViewHolder> {

private Realm realm;
private PersonFragment personFragment;
private OrderedRealmCollection<Person> adapterData;

public PersonAdapter(PersonFragment fragment, Realm realm, OrderedRealmCollection<Person> collection) {
    super(collection, true, true);
    this.realm = realm;
    this.adapterData = collection;
    this.personFragment = fragment;
    setHasStableIds(true);
}

@Override
public int getItemViewType(int position) {
    return (position == adapterData.size()) ? R.layout.rrv_button_add : R.layout.rrv_item;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// see example above
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    Person person = getData().get(position);
    PersonHolder personHolder = (ProductHolder) holder;
    if(position == adapterData.size()){
        //personHolder.button.setOnClickListener
    }
    else {
        personHolder.name.setText(person.getName());
    }
}

@Override
public long getItemId(int index) {
    return getItem(index).getId();
}

@Override
public int getItemCount() {
    return isDataValid() ? adapterData.size()+1 : 0;
}

private boolean isDataValid() {
    return adapterData != null && adapterData.isValid();
}

public class ProductHolder
        extends RecyclerView.ViewHolder {
// all that's needed
}

}

I feel that the solution is on the surface, but I am completely de-energized. Please point to my mistake

Dereva
  • 23
  • 1
  • 6
  • It's because a `RealmObject` does not exist at the index of your hacky button (which also isn't declared as its own ViewType using `getItemViewType`). – EpicPandaForce Apr 03 '18 at 18:22
  • i.e. the array has become larger by one index?.Okay.. So should i create Button ex.RealmObject and fasten it to the adapter as 2nd object? I've already seen something like this here.. (declaring button as VT i just didnt write here, it's similar to the example i indicated) – Dereva Apr 03 '18 at 19:16
  • use `getItemViewType`. As the extra item is at the end, it'll probably not mess with Realm's "ordered collection change" listener that works by indices – EpicPandaForce Apr 03 '18 at 22:04

0 Answers0