I'm having a nullpointer error and I do not know how to fix

2

The code I'm using is this:

public ForumGroups getMainGroup() {
        if (Constants.SQL_ENABLED) {
            int lowest = -1;
            ForumGroups g = null;
            for (ForumGroup group : forumGroups) {
                if (group.getGroup().ordinal() < lowest || g == null) {
                    lowest = group.getGroup().ordinal();
                    g = group.getGroup();
                }
            }
            if (g == null)
                return ForumGroups.MEMBER;
            else
                return g;
        }
        return ForumGroups.OWNER;
    }

And I'm getting error on this line

if (group.getGroup().ordinal() < lowest || g == null) {

What do I do?

error here:

java.lang.NullPointerException
    at ophion.rs.game.player.Player.getMainGroup(Player.java:4118)
    at ophion.rs.game.player.Player.InterfaceManager$3.run(InterfaceManager.java:472)
    at ophion.rs.game.tasks.WorldTasksManager.processTasks(WorldTasksManager.java:18)

    
asked by anonymous 27.08.2015 / 16:08

2 answers

1

The NullPointerException happens when you try to access a member (variable or method) of a object that has a null reference .

In your code if (group.getGroup().ordinal() < lowest || g == null) { , 2 objects can be null: group or group.getGroup() .

So, the exception occurs or when it attempts to execute the method group.getGroup() or group.getGroup().ordinal() .

So you need to check if these values are null before checking the group.getGroup().ordinal() method, so:

if( (null != group && null != group.getGroup() && group.getGroup.ordinal() < lowest) || g == null)

See if the if is too long and this can be difficult to understand. So you can create a method for null checks:

private boolean isGroupNull(Group g){
  return null != g && null != g.getGroup();
}

and use this in your previous if:

if ( (!isGroupNull(group) && group.getGroup.ordinal() < lowest) || g == null)

Note that we had to put an extra parenthesis, since we previously checked A || B .. now we are checking (C && A) || B

UPDATE:

Within the if you try to make 2 assignments that depend on the same check that we made to see if the objects are null. If they are invalid they will give you an error again as you reported.

So let's change the logic of if:

for (ForumGroup group : forumGroups) {
  if(!isGroupNull(group)){
    if (group.getGroup().ordinal() < lowest || g == null) {
      lowest = group.getGroup().ordinal();
      g = group.getGroup();
    }
  }
}

So you "take advantage" of the verification we did for both situations.

    
27.08.2015 / 18:51
2

You need to break this if into pieces, that is:

if( (group.getGroup() != null && group.getGroup().ordinal() < lowest) || g == null )

What is probably happening is that getGroup () is returning null (Demeter's law).

    
27.08.2015 / 18:39