【发布时间】:2017-01-24 07:51:22
【问题描述】:
我当然知道这个错误是什么意思,但我不知道如何删除它。 现在我正在尝试
private void removeFriendFromList() {
List<Friend> copy = new ArrayList<Friend>(globalSearchFriends);
for (Friend friend : globalSearchFriends) {
if (friend.equals(remove)) {
copy.remove(friend);
}
}
}
但这不起作用。 这是我的全局列表
private List<Friend> globalSearchFriends = new ArrayList<>();
我也在尝试迭代,但没有成功,或者我做错了什么。
我还需要在这里使用它:我在 api 中搜索朋友,这就像我在 EditText 中输入文本然后在我的适配器中看到该用户时一样,但这仅适用于少数成员,总是当我像“andrew”一样搜索然后我搜索“youko”我得到了错误。
private void serachFriend(final String query) {
etGlobalSearch.addTextChangedListener(new TextWatcherAdapter() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
FindFriend request = new FindFriend();
request.query = query;
request.query = s.toString().toLowerCase().trim();
backend.findFriend(request).enqueue(new Callback<ResponseFindFriend>() {
@Override
public void onResponse(Call<ResponseFindFriend> call, Response<ResponseFindFriend> response) {
synchronized (globalSearchFriends) {
globalSearchFriends.clear();
removeFriendFromList();
try {
if (response == null)
throw new Exception();
if (!response.isSuccessful())
throw new Exception();
if (response.body() == null)
throw new Exception();
if (response.body().results == null)
throw new Exception();
globalSearchFriends = response.body().results;
} catch (Exception e) {
Log.d("Blad", "sobie");
} finally {
gatherResults();
}
}
}
@Override
public void onFailure(Call<ResponseFindFriend> call, Throwable t) {
synchronized (globalSearchFriends) {
globalSearchFriends.clear();
removeFriendFromList();
gatherResults();
}
}
});
}
});
}
private void removeFriendFromList() {
List<Friend> copy = new ArrayList<Friend>(globalSearchFriends);
for (Friend friend : globalSearchFriends) {
if (friend.equals(remove)) {
copy.remove(friend);
}
}
}
private void gatherResults() {
removeFriendFromList();
for (Friend f : globalSearchFriends)
globalSearchFriends.add(f);
findedFriendsAdapter.setFriendList(globalSearchFriends);
}
任何相关的帮助,祝你有美好的一天! :)
编辑 我在这个案例中遇到了错误。
java.util.ConcurrentModificationException
for (Friend f : globalSearchFriends)
globalSearchFriends.add(f);
findedFriendsAdapter.setFriendList(globalSearchFriends);
在日志上我有:
at java.util.ArrayList$ArrayListIterator.next
【问题讨论】:
-
在迭代列表的同时修改列表时应该使用迭代器。
-
请提供 real minimal reproducible example 和匹配的堆栈跟踪。迭代一个列表时,从另一个列表中删除元素应该可以正常工作。所以我假设你的代码只显示了部分事实。并且只是为了记录:您在 Friends 类中是否覆盖等于?
-
@jitinsharma 他没有在迭代时修改列表。他正在操纵该列表的副本!
-
globalSearchFriends.clear(); removeFriendFromList();列表已经为空,您正在对其进行迭代。 -
我告诉过你。请阅读minimal reproducible example!还有:堆栈跟踪!