我这里有一个复杂的问题。
我用一些数据初始化RecyclerView,但异步地从Web服务中获取数据,我想使用这些数据以便将其包含在RecyclerView中,但由于我的RecyclerView已被初始化,所以“太迟了”。 >
这是一些代码:
首先,我要用一些数据初始化Recyclerview
JSONArray medias; <- Global variable
ServiceProvider serviceProvider = new ServiceProvider(); <- Global variable where I'm doing my request
public void performRequest()
{
for (int j = 0; j < 3; j += 1) {
JSONObject newElem = new JSONObject();
newElem.put("path", "test");
newElem.put("state", "ongoing");
newElem.put("name", "element " + j);
medias.put(newElem);
serviceProvider.addMedia(getActivity(), new CallbackInterface() {
@Override
public void callbackaddMedia(Boolean success, JSONObject obj) {
if (success && obj != null)
{
//Here I want to use the response object like
//Update medias item state by obj.optString("state");
}
}
});
}
initRecyclerView();
}
private void initRecyclerView(){
adapter = new DocumentsAdapter(getActivity(),false, medias, this);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
binding.recyclerAll.setLayoutManager(mLayoutManager);
binding.recyclerAll.setItemAnimator(new DefaultItemAnimator());
binding.recyclerAll.setAdapter(adapter);
}
就像我说的那样,我正在异步地调用一个Webservice,每次给我一个这样的响应,每次带有不同的mediaId和状态:
{
"success": true,
"mediaId": "307",
"state": "success"
}
答案 0 :(得分:0)
就像评论中所说的那样,我使用了方法notifyDataSetChanged():
for (int k = 0; k < medias.length(); k += 1) {
JSONObject mediaObject = (JSONObject) medias.opt(k);
if (mediaObject.optString("gUid").equals(obj.optString("guid"))) {
mediaObject.put("state", obj.optString("state"));
mediaObject.put("id", obj.optString("mediaId"));
mediaObject.put("path", obj.optString("path"));
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (adapter != null) {
// I'm on my Fragment so I call my adapter like this , If you want to do this on your adapter , just call notifyDataSetChanged();
adapter.notifyDataSetChanged();
}
}
});
}
break;
}
}
我刚刚更新了在RecyclerView适配器中发送的JSONArray“媒体”中的一项。 然后,我在MAINTHREAD上调用了notifyDataSetChanged()。它将自动更新JSONArray中的所有值,并因此更改布局中的值