I am working on developing a Bukkit plugin (the error is not related to bukkit or it's api, but I included the fact that I am using it for completeness, if you do not know what it is/haven't heared of it you should still be able to answer this question). The plugin I am working on is an anti chat spam plugin. I am getting a nullpointerexception for no apparent reason. Here is some code:
public class SpamListener implements Listener{
private HashMap<String, Long> lastMessage;
private HashMap<String, Integer> spamScore;
public void init(){
lastMessage = new HashMap<String, Long>();
spamScore = new HashMap<String, Integer>();
}
@EventHandler
public void playerChatEvent(AsyncPlayerChatEvent e){
if(AntiGrief.instance.config.getBoolean("antispam.enabled") && (!e.getPlayer().hasPermission("antigrief.spam.bypass"))){
Player player = e.getPlayer();
String name = player.getName();
int startingScore = spamScore.get(name); // <-- NullPointerException occurs here
//More spam checking code here
}
}
JavaPlugin class (main class, for those not familiar with bukkit):
spamListener = new SpamListener();
spamListener.init(); // <-- yes the method is being called, same error occurs if the hashmap is instantiated in the constructor and declaration
pm.registerEvents(spamListener, instance);
Stacktrace: http://pastebin.com/cciibpXp
Thanks in advance for any answers :)
I suspect the problem isn't spamScore
being null
- it's the value in the map being null, because you haven't populated the map. You're then trying to unbox that null
reference to an int
, and that fails. So think of your code like this:
Integer startingScoreReference = spamScore.get(name);
int startingScore = startingScoreReference.intValue();
Now obviously if startingScoreReference
is null
(which it will be if there's no entry for name
in your map) then the second line will cause a NullPointerException
.
So basically you need to either ensure that your map will always contain an entry for name
, or you need to handle the case where there's no such entry. For example, you might want:
Integer mapValue = spamScore.get(name);
int startingScore = mapValue == null ? 0 : mapValue.intValue();
(The intValue()
call could be a cast to int
instead, depending on your preference.)
See more on this question at Stackoverflow