1
votes

Added items to recyclerView not showing up until user scroll. I'm using websockets to communication. When user on server send message, server returns json which i'm parsing to model and I add it to recyclerview adapter. Item is added to recyclerview but it's not showing up until i scroll recyclerview up or down. I made a test, where i added static String with test Json and when i click on a button it will trigger the same method but with test data outside websocket and it add item on top of recyclerview.

Added items with this method are not showing up until user scroll :

WebSocket ws = factory.createSocket("wss://example.com/websocket");
ws.addListener(new WebSocketAdapter() {
            @Override
            public void onTextMessage(WebSocket websocket, String text) throws Exception {
                adapter.add(parseWs(text);
            }
});

private Discussion parseWs(String string) {
    discussion = new JSONObject(string).getJSONObject("data").toString();
    Gson gson = new Gson();
    return gson.fromJson(discussion, Discussion.class);
}

////////////Adapter class////////////
public void add(Discussion disc) {
    list.add(0,disc);
    notifyItemInserted(0);
}

If i add item from clicking on button, items are showing up normally without scrolling :

fab.setOnClickListener(v -> 
    adapter.add(parseWs(test));
    mRecyclerView.scrollToPosition(0);
);

I'm using nv-weboskcet-client java library.

1

1 Answers

0
votes

Not sure what you exactlty want, but try to use

notifyDataSetChanged();

May this will fix your problem.

If the call is asynchronous you have to use the Handler class to update your view.

Android and JavaRx:

https://mttkay.github.io/blog/2013/08/25/functional-reactive-programming-on-android-with-rxjava/

But just try it with the Handler class.

Handler handler = new Handler();
ws.addListener(new WebSocketAdapter() {
    @Override
    public void onTextMessage(WebSocket websocket, String text) throws Exception {
        handler.post(new Runnable(){
            adapter.add(parseWs(text);
        });
    }
});

Something like that should work :)

May you have to declare Handler handler as a field in your Activity.