Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

FirebaseRecyclerAdapter firing twice


I have a problem using FirebaseRecyclerAdapater, at first it was working fine but now this adapter is firing twice. The database reference is only referring one child, but it is always firing twice. The Toast with text "counter" will appear twice

FirebaseRecyclerAdapter<RequestVisit, RequestViewHolder> requestAdapter = 
    new FirebaseRecyclerAdapter<RequestVisit, RequestViewHolder>(
    RequestVisit.class,
    R.layout.seekerrequests_layout,
    RequestViewHolder.class,
    requestDatabase.child("2DBwmhGplGMoAlLy6337HZEShi93")
) {
@Override
protected void populateViewHolder(final RequestViewHolder viewHolder, RequestVisit model, int position) {
     Toast.makeText(getContext(), "counter" + 
     viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
    }
};
requestVisitList.setAdapter(requestAdapter);

Solution

  • A Firebase*Adapter shows a list of items, the child nodes under the location that you attach it to.

    If populateViewHolder gets called with two different positions, that means there are two children under requestDatabase.child("2DBwmhGplGMoAlLy6337HZEShi93").

    Keep in mind that if 2DBwmhGplGMoAlLy6337HZEShi93 is a child node with two properties, then your approach will call populateViewHolder for each of those properties.

    If you want to show only a single item in the RecyclerView, you can create a simple query with:

    FirebaseRecyclerAdapter<RequestVisit, RequestViewHolder> requestAdapter = 
        new FirebaseRecyclerAdapter<RequestVisit, RequestViewHolder>(
        RequestVisit.class,
        R.layout.seekerrequests_layout,
        RequestViewHolder.class,
        requestDatabase.orderByKey().equalTo("2DBwmhGplGMoAlLy6337HZEShi93")
    )