Search code examples
anylogic

NullPointerException when trying to access an agent from Main in AnyLogic


I am trying to send a message to an agent in a specific state from Main. I have already done this many times, but this time AnyLogic is returning the NullPointerException error.

Here is the code I am using to send the message:

User chosen_user = randomWhere(users, t -> t.inState(User.Inactive));
users.get(chosen_user.getIndex()).receive("message");

Using traceln(chosen_users.getIndex()) for printing the index, everything works fine. Just when I plug the index in the function get() it returns the error.

Even if I plug just a random number, let's say users.get(1).receive("message"), it still returns the same error (my population has 700 agents).

Any thoughts?


Solution

  • It will just be because no user is in the Inactive state at some particular time so your randomWhere call returns null.

    You also don't need the indirection of using the index; just send the message directly to it using the send function:

    if (chosen_users != null) {
       send("message", chosen_users);
    }
    

    (Your naming is misleading too since chosen_users is always one User agent (or null).)