-1

NovoAmor class:

package me.zpandakst.commands;

import me.zpandakst.sql.SQLCache;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class AmorC implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        Player p = (Player) sender;

        ItemStack rose = new ItemStack(Material.POPPY);
        ItemMeta rosemeta = rose.getItemMeta();
        rosemeta.setDisplayName(ChatColor.DARK_RED + args[0]);
        rose.setItemMeta(rosemeta);
        p.getInventory().addItem(rose);
        SQLCache.addAmores(p);
        return false;
    }
}

SQLCache class:

package me.zpandakst.sql;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class SQLCache {
    public static Connection con;

    public static boolean checkconnect() {
        return con != null;
    }

    public static PreparedStatement getStatement(String sql) {
        if(checkconnect()) {
            try {
                return con.prepareStatement(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static ResultSet getResult(String sql) {
        if(checkconnect()) {
            try {
                PreparedStatement ps = getStatement(sql);
                return ps.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String host = "localhost";
    public static String bank = "Teste";
    public static int port = 3306;

    public static void startConnection() {
        if(checkconnect()) {
            System.out.println("Já existe uma conexão MySQL aberta!");
        } else {
            try {
                System.out.println("Conectando ao MySQL...");
                con = DriverManager.getConnection(
                        "jdbc:mysql://" + host + ":" + port + "/" + bank + "?autoReconnect=true", "root", "");
                Bukkit.getConsoleSender().sendMessage("§a§lSQLAPI §fConexão §eSQLCache §finiciada com sucesso! ");
            } catch (SQLException e) {
                Bukkit.getConsoleSender().sendMessage("§c§lSQLAPI §fOcorreu um erro ao efetuar a conexão MySQL (§aClass: SQLCache§f)");
            }
        }
    }

    public static void disconnect() {
        try {
            con.close();
            Bukkit.getConsoleSender().sendMessage("§a§lSQLAPI §fConexão §eSQLCache §ffinalizada com sucesso!");
        } catch (SQLException e) {
            Bukkit.getConsoleSender().sendMessage("§c§lSQLAPI §fOcorreu um erro ao finalizar a conexão SQLCache.");
        }
    }


    public static Map<String, Integer> Amores = new HashMap<String, Integer>();

    public static int getAmoresConnection(String name) {
        try {
            PreparedStatement ps = getStatement("SELECT * FROM Amores WHERE NICK= ?");
            ps.setString(1, name);
            ResultSet rs = ps.executeQuery();
            rs.next();
            int Amores = rs.getInt("Amores");
            rs.close();
            ps.close();
        } catch (Exception localException) {
        }
        return 0;
    }

    public static void loadCache(String name) {
        Amores.put(name, getAmoresConnection(name));
    }

    public static Integer getAmores(Player p) {
        return Amores.get(p.getName());
    }

    public static void addAmores(Player p) {
        Amores.replace(p.getName(), Amores.getOrDefault(p.getName(), 0) + 1);
    }

    public static void updateData(Player p) {
        try {
            con.createStatement().executeUpdate("UPDATE `amores` SET `AMORES`='" + getAmores(p) + "', `NICK`='" + p.getName() + "' WHERE `UUID`='" + p.getUniqueId() + "';");
        } catch (SQLException e) {
        } finally {
            SQLCache.Amores.remove(p.getName());
        }
    }

}

Error:

[14:50:13] [Server thread/ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'novoamor' in plugin Diario v1.0.0
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:47) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:149) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at org.bukkit.craftbukkit.v1_16_R2.CraftServer.dispatchCommand(CraftServer.java:758) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.PlayerConnection.handleCommand(PlayerConnection.java:1697) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.PlayerConnection.a(PlayerConnection.java:1540) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.PacketPlayInChat.a(PacketPlayInChat.java:47) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.PacketPlayInChat.a(PacketPlayInChat.java:1) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.PlayerConnectionUtils.lambda$0(PlayerConnectionUtils.java:19) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.TickTask.run(SourceFile:18) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.IAsyncTaskHandler.executeTask(SourceFile:144) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.IAsyncTaskHandlerReentrant.executeTask(SourceFile:23) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.IAsyncTaskHandler.executeNext(SourceFile:118) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.MinecraftServer.ba(MinecraftServer.java:941) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.MinecraftServer.executeNext(MinecraftServer.java:934) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.IAsyncTaskHandler.executeAll(SourceFile:103) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.MinecraftServer.sleepForTick(MinecraftServer.java:917) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.MinecraftServer.w(MinecraftServer.java:850) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at net.minecraft.server.v1_16_R2.MinecraftServer.lambda$0(MinecraftServer.java:164) ~[spigot-1.16.3.jar:git-Spigot-2740d5a-890130b]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_311]
Caused by: java.lang.NullPointerException
        at me.zpandakst.sql.SQLCache.addAmores(SQLCache.java:94) ~[?:?]
        at me.zpandakst.commands.AmorC.onCommand(AmorC.java:23) ~[?:?]

The objective is that every time the command is given, the player receives a flower with the name entered in the command and it is placed in the database how many times he used it. If I'm not mistaken, it's that there's some misplaced information in the code. I'm new to java so I can't understand the error.

AlexKarev
  • 11
  • 1
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – rkosegi Dec 04 '21 at 18:36

1 Answers1

0

Firstly, you should check if the person that run the command is well a player (and not the console or a command block) like that :

if(!(sender instanceof Player)) { // not a player
   return false;
}
Player p = (Player) sender;

Then, your error appear because the p.getName() key isn't on the Map<String, Integer> Amores's map. So, such as the key isn't not present, it will return null, an empty value. But, you are using it. So, such as Java don't know how to manage it, it throw error.

You should use getOrDefault like that :

public static void addAmores(Player p) {
    Amores.replace(p.getName(), Amores.getOrDefault(p.getName(), 0) + 1);
}

Also, you have an error with getAmoresConnection method. Here, you never return the good value. In general, prefer use unique column such as UUID (instead of nickname column). You should do like that :

public static int getAmoresConnection(Player p) {
   try {
        PreparedStatement ps = getStatement("SELECT * FROM Amores WHERE UUID = ?");
        ps.setString(1, p.getUniqueId().toString());
        ResultSet rs = ps.executeQuery();
        if(rs.next()) // if you find the line
            return rs.getInt("Amores"); // return the given value
        rs.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return 0;
}

Finally, to save it in database, I suggest you to insert the line when the player join. But, let use say will not doing it. So, use this code :

public static void saveData(Player p, int amount) {
    try {
        if(!checkconnect()) // if no connection
           startConnection(); // make it
        PreparedStatement check = con.prepareStatement("SELECT * FROM Amores WHERE UUID = ?");
        check.setString(1, p.getUniqueId().toString());
        if(check.executeQuery().next()) { // the line exist, should update
           PreparedStatement updt = con.prepareStatement("UPDATE Amores SET ARMORES = ? WHERE UUID = ?");
           updt.setInt(1, amount);
           updt.setString(2, p.getUniqueId().toString());
           updt.executeUpdate(); // run update query. Now it's fine
        } else {
           PreparedStatement isn = con.prepareStatement("INSERT INTO Armores(AMORES, NICK, UUID) VALUES (?,?,?)");
           isn.setInt(1, amount);
           isn.setString(2, p.getName());
           isn.setString(3, p.getUniqueId().toString());
           isn.executeUpdate(); // run insert query. Now it's fine
        }
    } catch (SQLException e){
        e.printStackTrace(); // don't hide error !
    }
}

Then you have to call the method such as :

public static void addAmores(Player p) {
    int amount = Amores.getOrDefault(p.getName(), 0) + 1;
    Amores.put(p.getName(), amount);
    saveData(p, amount);
}
Elikill58
  • 4,050
  • 24
  • 23
  • 45