NullPointerException on 'getPlayer()'

Discussion in 'Plugin Development' started by twinflyer, Apr 25, 2012.

Thread Status:
Not open for further replies.
  1. Offline


    Hey Guys,
    at the moment I'm writing a lightweight Chatplugin for a server without Permissions System (OP and not-OP).
    Writing global works perfekt and private works nearly :S

    If soneone writes '/p twin' it searches for twin and starts a conversation with the player 'twinflyer'.
    But if 'twinflyer' is not online and/or the name is misspelled I get a NullPointerException.
    Of course getServer().getPlayer("twin"); returns null if "twin" if not there, but even a NullCheck didn't fix the Problem.

    if (args.length == 1) {
        String ToName = args[0];
        Player to = main.plugin.getServer().getPlayer(ToName);
        if (to != null) {
            ToName = to.getName();
            main.conservations.put(p.getName(), ToName);
            main.lastPMessage.put(ToName, p.getName());
            p.sendMessage(ChatColor.GRAY + "You started a conversation with " + ToName);
        } else {
            p.sendMessage(ChatColor.RED + "Player Not Found!");

    The Console says that the Exception is thrown on line 40 (the line where if (to != null) { is).
    How can I fix this Bug?


    Tried this solution, but it didn't work.

    The Exception is thrown in this line:
    if (main.plugin.getServer().getPlayer(ToName) != null) {
  2. Offline


    I would suggest checking if the player exists and is online like:
    if (to.isOnline() && to != null)
  3. Offline


    You should rather use .matchPlayer(String);
    It takes the closest match, use it like this:

    List<Player> matches = getServer().matchPlayer(s);
    if (matches.isEmpty())
    sender.sendMessage("Player not found");
    Player player = matches.get(0);
  4. Offline

    Father Of Time

    FYI, do the null check first; you can't call a function within an object that is null (which is what isOnline is).

    I'm sure this was one of those "wrote this in 2 seconds" typos, but should be noted none the less.

    Take care guy!
    WinX64 likes this.
  5. Offline


    I would use "Bukkit.getPlayer(args[0]);" instead of "String ToName = args[0]
    Player to = main.plugin.getServer().getPlayer(ToName);"
  6. Offline


    Tanks, I've got it now.
    But the Problem was something completely different.

    Eclipse exported an old version of my Plugin, where the Null Chack wasn't implemented yet. I really have no idea why this happened, but now everything works fine :D

Thread Status:
Not open for further replies.

Share This Page