我有这个方法
private void changeContacts() {
if (mOnlyDisplayContacts) {
listContact = fetchContactResponse(mView);
} else {
// Other code
}
contactAdapter = new ContactsAdapter(context, listContact, this);
mContactsList.setAdapter(mContactAdapter);
mContactAdapter.notifyDataSetChanged();
}
private List<Contact> fetchContactResponse(final String view) {
AsyncContactSearch mLoadContactTask = new AsyncContactSearch(context, limit, offset, view, search);
try {
listContacts = mLoadContactTask.execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return listContacts;
}
类任务
public class AsyncContactSearch extends AsyncTask<Void, Void, List<LinphoneContact>> {
private Context context;
private int limit, offset;
private String view, search;
public AsyncContactSearch(Context context, int limit, int offset, String view, String search) {
this.context = context;
this.limit = limit;
this.offset = offset;
this.view = view;
this.search = search;
}
@Override
protected List<Contact> doInBackground(Void... voids) {
String domain = SharedPreferencesManager.getDomain(context);
String authToken = SharedPreferencesManager.getAuthtoken(context);
final List<Contact> listContact = new ArrayList<>();
RestAPI RestAPI = RetrofitHelper.create(RestAPI.class, domain);
Call<ContactList> searchWithTerms =
userRestAPI.searchWithTerms(authToken, "", limit, offset);
searchWithTerms.enqueue(
new Callback<ContactList>() {
@Override
public void onResponse(Call<ContactList> call, Response<ContactList> response) {
ContactList contactList = response.body();
if (contactList == null) {
return;
}
List<Contact> contacts = contactList.getRows();
for (Contact c : contacts) {
listContact.add(
ContactsManager.getInstance().addFromAPI(c));
}
}
@Override
public void onFailure(Call<ContactList> call, Throwable throwable) {}
});
Collections.sort(
listContact,
new Comparator() {
public int compare(Object o1, Object o2) {
String x1 = ((LinphoneContact) o1).getCompany();
String x2 = ((LinphoneContact) o2).getCompany();
int sComp = x1.compareTo(x2);
if (sComp != 0) {
return sComp;
}
String x3 = ((LinphoneContact) o1).getFirstName();
String x4 = ((LinphoneContact) o2).getFirstName();
return x3.compareTo(x4);
}
});
return listContact;
}
}
问题是(调试代码),当搜索任务仍在运行时,该方法被立即触发contactAdapter = new ContactsAdapter(context, listContact, this);
listContact为空,然后执行继续将适配器分配给ListView,而恢复任务继续并将元素插入列表中,在屏幕上ListView仍然为空
您正在使用API调用的改造,因此不需要使用AsyncTask
。该改进将使API调用asynchronously
,并在callback onResponse()
中交付结果。只需将您的逻辑移到callback onResponse()
中。