0

I want that after writing any message, the user gets into the list. The first time it works, but as soon as another user writes, for some reason it shows null.

@Override
public void onUpdateReceived(Update update) {
    if (update.hasMessage() && update.getMessage().hasText()) {
        getLogs(update);
        addUser(update.getMessage().getChat().getUserName(), update.getMessage().getChatId());
    }
}

private void addUser(String name, long chatId) {
    Buddy buddy;
    if (!users.isEmpty()) {
        for (Buddy user : users) {
            if (name.equals(user.getName()) && chatId == user.getNameId()) {
                System.out.println("Exists");
            } else {
                buddy = new Buddy(name, chatId);
                users.add(buddy);
            }
        }
    } else {
        users.add(new Buddy(name, chatId));
    }
    System.out.println(users.toString());
}

I expected that after writing from any user, a unique Buddy would be added to the list, but for some reason this did not happen.

Catching such a mistake: java.util.ConcurrentModificationException: null

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
kikichs
  • 3
  • 2

1 Answers1

1

You are iterating through users:

for (Buddy user : users) {

while changing the users list:

buddy = new Buddy(name, chatId);
users.add(buddy);

== ConcurrentModificationException

You have to add the user, if not found, after you have finished the for loop.

Bill Mair
  • 1,073
  • 6
  • 15