我正在使用Retroofit beta1 2.0。
我正在为topstories.json调用hacker news api来获取项目ID。在第一个调用的onResponse()上,我遍历项目ID并再次调用" item / {itemid} .json"。
在第二次调用的onResponse()中,我设置了本地列表变量,其中Item类由Response.body()填充。我可以在日志中看到结果。
但我无法在RecyclerView UI中显示。请帮忙。
private final List<Item> mItemList = new ArrayList<>();
private final List<Integer> itemIdsList = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvEmptyView = (TextView) findViewById(R.id.empty_view);
mRecyclerView = (RecyclerView) findViewById(R.id.item_recycle);
handler = new Handler();
// load the data over network
loadData();
mRecyclerView.setHasFixedSize(true);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mDataAdapter = new DataAdapter(mItemList, mRecyclerView);
mRecyclerView.setAdapter(mDataAdapter);
mAdapter.notifyDataSetChanged();
}
private void loadData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://hacker-news.firebaseio.com/v0/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
final HackerNewsAPI hackerNewsAPI = retrofit.create(HackerNewsAPI.class);
Call<int[]> callItemIds = hackerNewsAPI.loadItems();
callItemIds.enqueue(new Callback<int[]>() {
@Override
public void onResponse(Response<int[]> response) {
int[] itemIds = response.body();
for (int i : itemIds) itemIdsList.add(new Integer(i));
for (int itemId : itemIdsList) {
Call<Item> callItems = hackerNewsAPI.loadItem(itemId + ".json");
callItems.enqueue(new Callback<Item>() {
@Override
public void onResponse(Response<Item> response) {
Item item = response.body();
mItemList.add(item);
}
@Override
public void onFailure(Throwable t) {
System.out.println("inside failure");
t.printStackTrace();
}
});
}
}
@Override
public void onFailure(Throwable t) {
}
});
}
答案 0 :(得分:0)
由于回调发生异步,您将要在onResponse主体中引用您的recyclerview适配器。将项目添加到适配器中的项目列表,然后通知数据集已更改或您已添加项目。