我正在从Websockets获取json并显示在recyler视图中。从Websocket获取数据时,如何实时更新列表?
我的WebSocket类
public final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
private static final String TAG = "DashBoardScreen.this";
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
最初建立连接后,我会向服务器发送一些文本
webSocket.send(builder.toString());
}
@Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
返回服务器向我发送数据
output(text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
Log.d(TAG, "onClosing: ");
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
Log.d(TAG, "onClosed: ");
}
@Override
public void onFailure(WebSocket webSocket, Throwable t,Response response) {
super.onFailure(webSocket, t, response);
Log.d(TAG, "onFailure: ");
}
}
输出方法
private void output(final String text) {
runOnUiThread(new Runnable() {
@Override
public void run() {
*parsing json inside recyler view*
try {
JSONObject object = new JSONObject(text);
StringBuilder builder = new StringBuilder();
if (object.getBoolean("status")) {
JSONArray jsonArray = object.getJSONArray("events");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject values = jsonArray.getJSONObject(i);
final EventsDataModel dataModel = new EventsDataModel(
values.getString("service_Room_Number"),
values.getString("service_Name"),
values.getString("service_AssignedTo"),
values.getString("service_ID")
);
eventsDataModels.add(dataModel);
adapter = new EventListAdapter(eventsDataModels, context);
eventRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
notifyDataSetChanged()的工作原理如何?
}
} else Toast.makeText(context, "No Events", Toast.LENGTH_SHORT).show();
System.out.println(builder.append(object.getString("status")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
答案 0 :(得分:0)
只要您的dataModel有新数据
eventsDataModels.add(dataModel);
adapter = new EventListAdapter(eventsDataModels, context);
eventRecyclerView.setAdapter(adapter);
如果执行上述操作并执行adapter.notifyDataSetChanged();
将通知适配器新数据已经到达,并且必须使用新的dataModel更新RecyclerView。