Ir para conteúdo
  • 0

Problema NullPointerException


Muloo

Pergunta

Olá, implementei uso de mysql/sqlite em kits no plugin essentials que estou fazendo para meu servidor e ao tentar pegar algum kit me deparo com o seguinte erro: 
 

[13:08:01 INFO]: Muloo issued server command: /kit vip
[13:08:01 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'kit' in plugin Essentials v0.1
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:641) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PlayerConnection.handleCommand(PlayerConnection.java:1162) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java:997) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(PacketPlayInChat.java:45) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(PacketPlayInChat.java:1) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:13) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_141]
        at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_141]
        at net.minecraft.server.v1_8_R3.SystemUtils.a(SourceFile:44) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:715) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:374) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:654) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:557) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_141]
Caused by: java.lang.NullPointerException
        at me.muloo.essentials.kits.CommandKit.onCommand(CommandKit.java:32) ~[?:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
        ... 15 more
[13:08:01 INFO]: Muloo issued server command: /kit vip
[13:08:01 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'kit' in plugin Essentials v0.1
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:641) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PlayerConnection.handleCommand(PlayerConnection.java:1162) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java:997) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(PacketPlayInChat.java:45) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(PacketPlayInChat.java:1) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:13) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_141]
        at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_141]
        at net.minecraft.server.v1_8_R3.SystemUtils.a(SourceFile:44) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:715) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:374) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:654) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:557) [spigot.jar:git-Spigot-db6de12-18fbb24]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_141]
Caused by: java.lang.NullPointerException
        at me.muloo.essentials.kits.CommandKit.onCommand(CommandKit.java:32) ~[?:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spigot.jar:git-Spigot-db6de12-18fbb24]
        ... 15 more

Linha do erro: 

if (Main.cooldown.containsCooldown(playerN, kit)) {

containsCooldown:

	public boolean containsCooldown(String player, String kit) {
		try {
			Statement statement = c.createStatement();
			ResultSet res = statement.executeQuery("SELECT * FROM kits WHERE Player = '" + player + "' AND kit = '"+ kit +"';");
			while (res.next()) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

Ja tentei até colocar só return false; e continua o mesmo erro.

e todos metodos da classe tambem da erro.

Segue abaixo as classes utilizadas para o comando kit:

CommandKit.class: 

package me.muloo.essentials.kits;

import java.util.concurrent.TimeUnit;

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 me.muloo.essentials.Main;
import me.muloo.essentials.Utils;
import me.muloo.essentials.utils.messages;

public class CommandKit implements CommandExecutor {
	public Main plugin;
	public CommandKit(Main plugin) {
		this.plugin = plugin;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String string, String[] args) {
		if(sender instanceof Player){
			Player player = (Player)sender;
			if(args.length == 1){
				if(Main.kits.contains("Kits." + args[0].toString())){
					String playerN = player.getName();
					String kit = args[0].toString();
					int cd = Main.kits.getInt("Kits." + args[0].toString() + ".cooldown");
					if(player.hasPermission("essentials.kit." + args[0].toString())){
			            if (Main.cooldown.containsCooldown(playerN, kit)) {
			            	player.sendMessage(messages.get("kitTimed").replace("&", "§").replace("{0}", Main.cooldown.getRemainingTime(playerN, kit, TimeUnit.SECONDS.toMillis(cd))));
			            } else {
			            	for (String s : Main.kits.getStringList("Kits." + args[0].toString() + ".items")) {
			            		String[] a = s.split(" ");
			            		String[] itemid = a[0].split(":");
			            		ItemStack i;
			            		if (itemid.length > 1) {
			            			i = new ItemStack(Integer.valueOf(itemid[0]).intValue(), Integer.valueOf(a[1]).intValue(), Byte.valueOf(itemid[1]).byteValue());
			            		} else {
			            			i = new ItemStack(Integer.valueOf(itemid[0]).intValue(), Integer.valueOf(a[1]).intValue());
			            		}
			            		if (a.length > 2) {
			            			for (int enchantposition = 2; enchantposition <= a.length - 1; enchantposition++) {
			            				String[] enchantnameandnivel = a[enchantposition].split(":");
			            				try {
			            					i.addEnchantment(Utils.getEnchants(enchantnameandnivel[0]), Integer.valueOf(enchantnameandnivel[1]).intValue());
			            				} catch (Exception IllegalArgumentException) {
			            					player.sendMessage(messages.get("kitError").replace("&", "§"));
			            				}
			            			}
			            		}
			            		player.getInventory().addItem(new ItemStack[] { i });
			                }
			                player.sendMessage(messages.get("kitReceive").replace("&", "§").replace("{0}", args[0]));
			                Main.cooldown.setCooldown(playerN, kit);
			            }
					} else {
						player.sendMessage(messages.get("noKitPermission").replace("&", "§"));
					}
				} else {
					player.sendMessage(messages.get("kitNotFound").replace("&", "§"));
				}
			} else {
		        player.sendMessage(messages.get("argsError").replace("&", "§").replace("{0}", "/kit <kitname>"));
		    }
			return true;
		} else {
			sender.sendMessage(messages.get("onlyPlayers").replace("&", "§"));
		}
		return false;
	}

}

Cooldown.class: 

package me.muloo.essentials.kits;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.muloo.essentials.mysql.SQLManager;
import me.muloo.essentials.utils.messages;

public class Cooldown {
	private static Connection c = null;
	
	public static void loadDataBase() {
		c = SQLManager.c;
		SQLManager.createTables("CREATE TABLE IF NOT EXISTS `kits`(`Player` VARCHAR(20) NOT NULL, `kit` VARCHAR(20) NOT NULL, `time` INT NOT NULL);");
	}
	
	public void setCooldown(String player, String kit) {
		try {
			Statement statement = c.createStatement();
			statement.executeUpdate("INSERT INTO kits (`Player`, `kit`, `time`) VALUES ('" + player + "', '"+ kit +"', "+ System.currentTimeMillis() +");");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public long getCooldown(String player, String kit) {
		if(containsCooldown(player, kit)) {
			return getLong(player, kit);
		} else {
			return System.currentTimeMillis();
		}
	}
	
	private long getLong(String player, String kit) {
		long l = 0;
		try {
			Statement statement = c.createStatement();
			ResultSet res = statement.executeQuery("SELECT * FROM kits WHERE Player = '" + player + "' AND kit = '"+ kit +"';");
			res.next();
			return res.getLong("time");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return l;
	}
	
	public boolean isExpired(String player, String kit, long l) {
		String coisa = getRemainingTime(player, kit, l);
		if (coisa.contains(messages.get("now"))) {
			return true;
		} else {
			return false;
		}
	}
	
	public String getRemainingTime(String player, String kit, long l) {
		long tempoAntes = getCooldown(player, kit);
		long tempoAtual = System.currentTimeMillis() - l;
		String coisa = formatDifferenceStr((tempoAntes - tempoAtual));
		return coisa;
	}
	
	public void removeCooldown(String player, String kit) {
		try {
			PreparedStatement ps = c.prepareStatement("DELETE FROM `kits`(Player, kit) VALUES (?, ?);");
			ps.setString(1, player);
			ps.setString(2, kit);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public boolean containsCooldown(String player, String kit) {
		try {
			Statement statement = c.createStatement();
			ResultSet res = statement.executeQuery("SELECT * FROM kits WHERE Player = '" + player + "' AND kit = '"+ kit +"';");
			while (res.next()) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	
	public String formatDifferenceStr(long time) {
		if (time == 0) {
			return "never";
		}
		long day = TimeUnit.MILLISECONDS.toDays(time);
		long hours = TimeUnit.MILLISECONDS.toHours(time) - (day * 24);
		long minutes = TimeUnit.MILLISECONDS.toMinutes(time) - (TimeUnit.MILLISECONDS.toHours(time) * 60);
		long seconds = TimeUnit.MILLISECONDS.toSeconds(time) - (TimeUnit.MILLISECONDS.toMinutes(time) * 60);
		StringBuilder sb = new StringBuilder();
		if (day > 0) {
			sb.append(day).append(" ").append(day == 1 ? messages.get("day") : messages.get("dias")).append(" ");
		}
		if (hours > 0) {
			sb.append(hours).append(" ").append(hours == 1 ? messages.get("hour") : messages.get("hours")).append(" ");
		}
		if (minutes > 0) {
			sb.append(minutes).append(" ").append(minutes == 1 ? messages.get("minute") : messages.get("minutes")).append(" ");
		}
		if (seconds > 0) {
			sb.append(seconds).append(" ").append(seconds == 1 ? messages.get("second") : messages.get("seconds"));
		}
		String diff = sb.toString();
		return diff.isEmpty() ? messages.get("now") : diff;
	}

	public String getDifferenceFormatStr(long timestamp) {
		return formatDifferenceStr(timestamp - (System.currentTimeMillis()));
	}

	// Copyright essentials, all credits to them for this.
	public long parseDateDiff(String time, boolean future) throws Exception {
		Pattern timePattern = Pattern.compile("(?[0-9]+)\\s*y[a-z]*[,\\s]*)?" + "(?[0-9]+)\\s*mo[a-z]*[,\\s]*)?"
				+ "(?[0-9]+)\\s*w[a-z]*[,\\s]*)?" + "(?[0-9]+)\\s*d[a-z]*[,\\s]*)?"
				+ "(?[0-9]+)\\s*h[a-z]*[,\\s]*)?" + "(?[0-9]+)\\s*m[a-z]*[,\\s]*)?"
				+ "(?[0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
		Matcher m = timePattern.matcher(time);
		int years = 0;
		int months = 0;
		int weeks = 0;
		int days = 0;
		int hours = 0;
		int minutes = 0;
		int seconds = 0;
		boolean found = false;
		while (m.find()) {
			if (m.group() == null || m.group().isEmpty()) {
				continue;
			}
			for (int i = 0; i < m.groupCount(); i++) {
				if (m.group(i) != null && !m.group(i).isEmpty()) {
					found = true;
					break;
				}
			}
			if (found) {
				if (m.group(1) != null && !m.group(1).isEmpty()) {
					years = Integer.parseInt(m.group(1));
				}
				if (m.group(2) != null && !m.group(2).isEmpty()) {
					months = Integer.parseInt(m.group(2));
				}
				if (m.group(3) != null && !m.group(3).isEmpty()) {
					weeks = Integer.parseInt(m.group(3));
				}
				if (m.group(4) != null && !m.group(4).isEmpty()) {
					days = Integer.parseInt(m.group(4));
				}
				if (m.group(5) != null && !m.group(5).isEmpty()) {
					hours = Integer.parseInt(m.group(5));
				}
				if (m.group(6) != null && !m.group(6).isEmpty()) {
					minutes = Integer.parseInt(m.group(6));
				}
				if (m.group(7) != null && !m.group(7).isEmpty()) {
					seconds = Integer.parseInt(m.group(7));
				}
				break;
			}
		}
		if (!found) {
			throw new Exception("Illegal Date");
		}
		if (years > 20) {
			throw new Exception("Illegal Date");
		}
		Calendar c = new GregorianCalendar();
		if (years > 0) {
			c.add(Calendar.YEAR, years * (future ? 1 : -1));
		}
		if (months > 0) {
			c.add(Calendar.MONTH, months * (future ? 1 : -1));
		}
		if (weeks > 0) {
			c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1));
		}
		if (days > 0) {
			c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1));
		}
		if (hours > 0) {
			c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1));
		}
		if (minutes > 0) {
			c.add(Calendar.MINUTE, minutes * (future ? 1 : -1));
		}
		if (seconds > 0) {
			c.add(Calendar.SECOND, seconds * (future ? 1 : -1));
		}
		return c.getTimeInMillis();
	}

SQLManager.class: 

package me.muloo.essentials.mysql;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.bukkit.configuration.file.FileConfiguration;

import me.muloo.essentials.Main;
import me.muloo.essentials.mysql.mysql.MySQL;
import me.muloo.essentials.mysql.sqlite.SQLite;

public class SQLManager {
	private static MySQL MySQL = new MySQL(Main.plugin.getConfig().getString("MySQL.host"), Main.plugin.getConfig().getString("MySQL.port"), 
			Main.plugin.getConfig().getString("MySQL.database"), Main.plugin.getConfig().getString("MySQL.user"), Main.plugin.getConfig().getString("MySQL.password"));
	private static SQLite SQLite = new SQLite("data.db");
	public static Connection c = null;
	
	public static void SQLManagerConnection() {
		if(getConfig().getBoolean("MySQL.enable")) {
			MySQLConnection();
		} else {
			SQLiteConnection();
		}
	}
	
	public static void createTables(String code) {
		try {
			Statement statement = c.createStatement();
			statement.executeUpdate(code);
			System.out.print("Table created");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private static void MySQLConnection() {
		try {
			c = MySQL.openConnection();
			System.out.print("MySQL Hooked");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}
	
	private static void SQLiteConnection() {
		try {
			c = SQLite.openConnection();
			System.out.print("SQLite Hooked");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}
	
	private static FileConfiguration getConfig() {
		return Main.plugin.getConfig();
	}
}

na Main estou usando em onEnable():

   SQLManager.SQLManagerConnection();
   Cooldown.loadDataBase();
para carregar o database.
Link para o comentário
Compartilhar em outros sites

7 respostass a esta questão

Posts Recomendados

A variável cooldown foi iniciada? Mostra as linhas onde você usou a variável na main


	public static Main plugin;
	public static FileConfiguration config;
	public static YamlConfig messages;
	public static YamlConfig locations;
	public static YamlConfig kits;
	public static Cooldown cooldown;
	@Override
	public void onEnable() {
		plugin = this;

		getLogger().info("§3[Essentials] §aHabilitado");
		
		config = getConfig();
		createFiles();
		saveDefaultConfig();

	    registerEvents();
	    loadCommands();
	    loadAliases();
	    SQLManager.SQLManagerConnection();
	    Cooldown.loadDataBase();
	}
Link para o comentário
Compartilhar em outros sites


	public static Main plugin;
	public static FileConfiguration config;
	public static YamlConfig messages;
	public static YamlConfig locations;
	public static YamlConfig kits;
	public static Cooldown cooldown;
	@Override
	public void onEnable() {
		plugin = this;

		getLogger().info("§3[Essentials] §aHabilitado");
		
		config = getConfig();
		createFiles();
		saveDefaultConfig();

	    registerEvents();
	    loadCommands();
	    loadAliases();
	    SQLManager.SQLManagerConnection();
	    Cooldown.loadDataBase();
	}

vc só abriu a variavel n disse o que ela é '-

public static Cooldown cooldown;

cooldown = ....;

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novos posts.
×
×
  • Criar Novo...