【发布时间】:2021-01-31 05:38:48
【问题描述】:
总结一下我的问题:
我有一个项目列表和一个按钮,我可以单击它来查询 API
当我单击按钮时,会调用两个方法。第一种方法显示进度条,清空列表,使用notifyDataSetChanged()
public void methodOne(){
mProgressBar.setVisibility(View.VISIBLE);
mList.clear;
mAdapter.notifyDataSetChanged();
}
第二种方法使用retrofit进行查询,在回调方法中,我隐藏进度条,添加到列表中调用notifyDataSetChanged();
public void methodTwo(){
RetrofitInterfaces.SearchForPosts service = RetrofitClientInstance.getRetrofitInstance()
.create(RetrofitInterfaces.SearchForPosts.class);
Call<Feed> call = service.listRepos(url);
call.enqueue(new Callback<Feed>() {
@Override
public void onResponse(@NonNull Call<Feed> call, @NonNull Response<Feed> response) {
try{
mProgressBar.setVisibility(View.INVISIBLE);
mList.addAll(response.body().getData());
mAdapter.notifyDataSetChanged();
} catch(Exception e){
Log.e(TAG, "Error: " + e);
}
}
@Override
public void onFailure(@NonNull Call<Feed> call, @NonNull Throwable t) {
Log.e(TAG, "onFailure: " + t);
}
});
}
}
我的问题是当我一个接一个地调用这两个时:
methodOne();
methodTwo();
第二个带有改造调用的方法有时会返回一个 IndexOutOfBounds 异常,因为我在编辑 mList 时 methodOne() 调用了 mList.clear() 和 mAdapter.notifyDataSetChanged();。
我的问题是如何让这两者原子发生,这样它们就不会相互干扰? (我希望 methodOne() 甚至在查询发生在 methodTwo 之前做所有事情)
【问题讨论】:
标签: android android-recyclerview retrofit retrofit2 android-threading