vihkat
vihkat

Reputation: 1005

Android FirebaseRecyclerAdapter refresh all item

I have an FirebaseRecyclerAdapter. I want to numbering items. So if i have 5 item, like

1 - d 
2 - w
3 - c
4 - s 
5 - z

when i add a new item to first place than: (i need to do it)

1 - g
2 - d 
3 - w
4 - c
5 - s 
6 - z

So i want to add a new Position number to all item when a new item arrive.So i want to refresh all position. How can i do it?

// Set up Layout Manager, reverse layout
        mManager = new LinearLayoutManager(getActivity());
        mManager.setReverseLayout(true);
        mManager.setStackFromEnd(true);
        mRecycler.setLayoutManager(mManager);

        // Set up FirebaseRecyclerAdapter with the Query
        Query postsQuery = getQuery(mDatabase);
        mAdapter = new FirebaseRecyclerAdapter<Test, PostViewHolder>(Test.class, R.layout.item_record, PostViewHolder.class, postsQuery) {
            @Override
            protected void populateViewHolder(final PostViewHolder viewHolder, final Test model, final int position) {
                viewHolder.bindToPost(model);
            }

        };
        mRecycler.setAdapter(mAdapter);

.

public class PostViewHolder extends RecyclerView.ViewHolder {

    public TextView titleView;

    public PostViewHolder(View itemView) {
        super(itemView);
        titleView = (TextView) itemView.findViewById(R.id.tview);
    }

    public void bindToPost(Test item) {
        titleView.setText(String.valueOf(getLayoutPosition())+". "+item.name);
    }
}

When a new item arrive, than populateViewHolder is run 1 time. But old items isn't refreshed. How can i refresh all?

getLayoutPosition() do it:

5 - g
4 - d 
3 - w
2 - c
1 - s 
0 - z

How can i refresh all item, when one new created?

Upvotes: 0

Views: 1553

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You're not showing your Query. It needs to have a sort order defined so that when new items arrive or are changed, the Query can automatically reflect those changes.

Since you want to sort on some sort of position index, you'll also need to add a position field to your data so that the query can order using that child key.

The bottom line is this: If you Query defines an ordering, and the ordering of the children changes over time, FirebaseRecyclerAdapter will automatically reflect those changes. You just need to make sure the data is correct in the database.

If you can't create a Query that correctly orders the data, you should probably not use FirebaseRecyclerAdapter, and instead read the data using a listener, then manually sort the data in your code, then send that to a custom adapter to display in the RecyclerView.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

To get the adapter to refresh its contents, notify it that the data set has changed:

mAdapter.notifyDataSetChanged();

Upvotes: 1

Related Questions