Android recyclerview update item with socket after sort

Viewed 24

How can update a specific item in Recyclerview without having a position?

I have a list that I fill first through the REST. And then any data that has changed from the server side, I will update it through the socket.

To update, needed a postion of the item. For this, I consider a position for each item by default (static) from the server side, but the problem arises when the user side sorts that list. (just sorted in localy)

After sorting, the positions of the items are messed up, and for this reason, it is no longer possible to update them through the statically defined positions.

How can i do this ?

Thanks for ideas!

1 Answers

I made it by below function:

private int findPosition(int staticPosition) {
        for (int i = 0; i < dataList.size(); i++) {
            if(dataList.get(i).getPosition() == staticPosition) {
                return i;
            }
        }
        return 0;
}

Maybe it's bad idea, but working perfectly. You can find position of item in the list after sort or by default.

Full code:

Gson gson = new Gson();
    public Emitter.Listener onNewMessage = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {

            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        String s = args[0].toString();
                        Type type = new TypeToken< List<List<int>>>(){}.getType();
                        List<List<int>> list  = gson.fromJson(s, type);
                        for (int i = 0; i < list.size(); i++) {
                            List<int> single = list.get(i);

                            int staticPostion     = single.get(0);
                            int price          = single.get(1);

                            if(marketAdapter != null) {
                                int postion =  findPosition(staticPostion);
                                dataList.get(postion).setPrice(price);
                                marketAdapter.notifyItemChanged(postion);
                            }
                        }

                    }
                });
            }

        }
    };
Related