gpt4 book ai didi

java - 如何解决我的代码中的 ConcurrentModificationException?

转载 作者:行者123 更新时间:2023-12-02 09:51:30 27 4
gpt4 key购买 nike

自过去两个小时以来,我一直在尝试解决此异常..我得到了抛出异常的代码行..但没有找到解决方案..请帮助我发生错误@ mUsers.add(user);//在其他部分

private void readChats()
{

mUsers = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addValueEventListener(new ValueEventListener()
{

@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
mUsers.clear();

for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);

//displaying 1 user from chat
for (String id : usersList) {
if (user.getUserId().equals(id)) {
if (mUsers.size() != 0) {
for (User user1 : mUsers) {
if (!user.getUserId().equals(user1.getUserId())) {
mUsers.add(user);
}
}
} else {
mUsers.add(user);

}
}
}

}//end of for

userAdapter = new UserAdapter(getContext(), mUsers);
recyclerView.setAdapter(userAdapter);

}
catch (Exception e)
{
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});



}//end of readChats
//this is the method

最佳答案

因为您正在编辑相同的ArrayList,所以您正在检索数据。因此,它会导致数据访问的同时进行修改的并发性。

尝试编辑复制的数据:

ArrayList<User> tempList = mUsers;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);

//displaying 1 user from chat
for (String id : usersList) {
if (user.getUserId().equals(id)) {
if (mUsers.size() != 0) {
for (User user1 : mUsers) {
if (!user.getUserId().equals(user1.getUserId())) {
tempList.add(user);
}
}
} else {
tempList.add(user);
}
}
}
}//end of for

//Copy temp list to main list.
mUsers.addAll(tempList);

userAdapter = new UserAdapter(getContext(), mUsers);
recyclerView.setAdapter(userAdapter);

关于java - 如何解决我的代码中的 ConcurrentModificationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56302253/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com