ArrayList$Itr.next 抛出错误 concurrentModificationException
Posted
技术标签:
【中文标题】ArrayList$Itr.next 抛出错误 concurrentModificationException【英文标题】:ArrayList$Itr.next throwing error concurrentModificationException 【发布时间】:2020-09-25 18:18:04 【问题描述】:我正在创建一个simple message app
,每次我在new user to message
上click
并单击send icon
后,我在readChats()
onDataChanged(@NonNull DataSnapshot dataSnapshot)
function
中收到以下错误concurrentModificationException in ArrayList
。我进行了研究,遇到了Iterator
,但不确定如何将implement
写入我的代码。
代码
public class ChatsFragment extends Fragment
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> mUsers;
FirebaseUser fuser;
DatabaseReference reference;
private List<String> usersList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_chats, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fuser = FirebaseAuth.getInstance().getCurrentUser();
usersList = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
usersList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
Chat chat = snapshot.getValue(Chat.class);
if (chat.getSender().equals(fuser.getUid()))
usersList.add(chat.getReceiver());
if (chat.getReceiver().equals(fuser.getUid()))
usersList.add(chat.getSender());
readChats();
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
);
return view;
private void readChats()
mUsers = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
mUsers.clear();
//Display 1 user from chats
for (DataSnapshot snapshot : dataSnapshot.getChildren())
User user = snapshot.getValue(User.class);
for (String id : usersList)
if (user.getId().equals(id))
if (mUsers.size() != 0)
for (User user1 : mUsers)
if (!user.getId().equals(user1.getId()))
mUsers.add(user);
else
mUsers.add(user);
userAdapter = new UserAdapter(getContext(), mUsers, true);
recyclerView.setAdapter(userAdapter);
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
);
【问题讨论】:
【参考方案1】:这个循环发生concurrentModificationException
for (User user1 : mUsers)
if (!user.getId().equals(user1.getId()))
mUsers.add(user);
因为你在扔mUsers
的物品时修改了mUsers
这样做
boolean containsUser = false;
for (User user1 : mUsers)
if (user.getId().equals(user1.getId()))
containsUser = true;
if (!containsUser)
mUsers.add(user);
【讨论】:
以上是关于ArrayList$Itr.next 抛出错误 concurrentModificationException的主要内容,如果未能解决你的问题,请参考以下文章