Search code examples
androidfirebasefirebase-realtime-databaseindexoutofboundsexceptionfirebaseui

IndexOutOfBoundsException on getRef().removeValue in FirebaseRecyclerAdapter


I'm getting this exception:

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

When using this code:

mAdapter = new FirebaseRecyclerAdapter<Campaign, CampaignHolder>(Campaign.class, R.layout.recyclerview_template, CampaignHolder.class, ref) {
        @Override
        public void populateViewHolder(final CampaignHolder viewHolder, final Campaign campaign, final int position) {
            final String key = campaign.x;
            FirebaseDatabase.getInstance().getReference().child("x").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!dataSnapshot.hasChild(key)) {
                        getRef(position).removeValue(new DatabaseReference.CompletionListener() { //Crash here
                            @Override
                            public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                                if (databaseError != null)
                                    FirebaseCrash.report(databaseError.toException());
                                else{
                                    if (mAdapter.getItemCount() == 0){
                                        v.findViewById(R.id.empty).setVisibility(View.VISIBLE);
                                    }
                                }

                            }
                        });

                        return;
                    }
                    //...
            }

At this line:

  getRef(position).removeValue(new DatabaseReference.CompletionListener() {

(I replaced some strings with x because I want to keep em private)


What's causing this issue? How can I fix it?


Solution

  • I solved it by putting this:

    DatabaseReference ref = getRef(position);
    

    Outside of the inner class, and then using ref instead of getRef(). This solved it for me, at least I think.