Java NullPointException Bukkit Plugin - java

I'm having a NullPointerException when trying to load the plugin in my bukkit server, but no errors in Eclipse. My plugin is a Rush pluing and alot of things are not used/missing.
The Error is this:
[18:11:10] [Server thread/ERROR]: Could not load 'plugins\rush.jar' in folder 'plugins'
org.bukkit.plugin.InvalidPluginException: java.lang.NullPointerException
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:182) ~ [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:308) ~ [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:231) [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at org.bukkit.craftbukkit.v1_7_R1.CraftServer.loadPlugins(CraftServer.java:255) [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at org.bukkit.craftbukkit.v1_7_R1.CraftServer.<init>(CraftServer.java:233) [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at net.minecraft.server.v1_7_R1.PlayerList.<init>(PlayerList.java:63) [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at net.minecraft.server.v1_7_R1.DedicatedPlayerList.<init>(SourceFile:14) [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at net.minecraft.server.v1_7_R1.DedicatedServer.init(DedicatedServer.java:126) [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at net.minecraft.server.v1_7_R1.MinecraftServer.run(MinecraftServer.java:424) [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
at net.minecraft.server.v1_7_R1.ThreadServerApplication.run(SourceFile:617) [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
Caused by: java.lang.NullPointerException
at me.mailh.Rush.MainRush.<init>(MainRush.java:62) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.7.0_45]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.7.0_45]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~ [?:1.7.0_45]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.7.0_45]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:178) ~ [craftbukkit.jar:git-Bukkit-1.7.2-R0.2-b2974jnks]
... 9 more
Here is my code:
package me.mailh.Rush;
import java.io.File;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
import org.bukkit.scoreboard.Team;
public class MainRush extends JavaPlugin implements Listener{
public final Logger logger = Logger.getLogger("Minecraft");
public static MainRush plugin;
public void onEnable(){
this.logger.info("Rush is enabled.");
getServer().getPluginManager().registerEvents(this, this);
}
private ScoreboardManager manager = Bukkit.getScoreboardManager();
private Scoreboard board = manager.getNewScoreboard();
private Team bleu = board.registerNewTeam("bleu");
private Team orange = board.registerNewTeam("orange");
public void onDisable(){
this.logger.info("Rush is disabled.");
}
public boolean onCommand(CommandSender s, Command c, String lbl, String[] args){
Player pl = (Player) s;
if (lbl.equalsIgnoreCase("rush")){
if (args.length == 0){
World w = Bukkit.getWorld("rush");
Location rush = new Location( w, -210, 51, -8 );
pl.sendMessage(ChatColor.GOLD + "Teleportation...");
pl.teleport(rush);
}
if (args[0].equalsIgnoreCase("bleu")){
board.resetScores(pl.getPlayer());
orange.removePlayer(pl.getPlayer());
bleu.addPlayer(pl.getPlayer());
pl.sendMessage(ChatColor.AQUA + "Vous êtes dans l'équipe bleu");
bleu.setAllowFriendlyFire(false);
}
if (args[0].equalsIgnoreCase("leave")){
board.resetScores(pl.getPlayer());
bleu.removePlayer(pl.getPlayer());
orange.removePlayer(pl.getPlayer());
pl.sendMessage(ChatColor.RED + "Vous avez quitté votre équipe");
}
if (args[0].equalsIgnoreCase("orange")){
board.resetScores(pl.getPlayer());
bleu.removePlayer(pl.getPlayer());
orange.addPlayer(pl.getPlayer());
pl.sendMessage(ChatColor.GOLD + "Vous êtes dans l'équipe orange");
orange.setAllowFriendlyFire(false);
}
}
return true;
}
public void rollback(){
if(Bukkit.getServer().unloadWorld("rush",false))
{
new File("rush").delete();
Bukkit.getServer().createWorld(new WorldCreator("rush"));
}
}
#EventHandler
public void onLeave(PlayerQuitEvent e){
Player p = (Player) e.getPlayer();
bleu.removePlayer(p);
orange.removePlayer(p);
board.resetScores(p);
}
#EventHandler
public void Death(PlayerDeathEvent event){
if (event.getEntityType() == EntityType.PLAYER){
Player player = event.getEntity();
Team team = board.getPlayerTeam(player);
if(team.equals(bleu)){
player.sendMessage("did it work? bleu");
}
else if (team.equals(orange)){
player.sendMessage("did it work orange?");
}
}
}
}

It seems to this code:
private ScoreboardManager manager = Bukkit.getScoreboardManager();
private Scoreboard board = manager.getNewScoreboard();
The reason is that you're not declaring these variables inside of a method, so, they get loaded before your onEnable() method is called, making it so that you can't get anything using Bukkit as it Bukkit has not yet been initialized.
What I recommend doing is doing something like this outside of any methods:
private ScoreboardManager manager;
private Scoreboard board;
then doing this in your onEnable():
manager = Bukkit.getScoreboardManager();
board = manager.getNewScoreboard();
So you would have something like this:
public class MainRush extends JavaPlugin implements Listener{
private ScoreboardManager manager;
private Scoreboard board;
#Override
public void onEnable(){
//plugin enabled
manager = Bukkit.getScoreboardManager();
board = manager.getNewScoreboard();
}
}
By doing this, you're eliminating the chance of getting a NullPointerException when your plugin is loaded. As a general rule of thumb, you should never get anything from bukkit outside of methods.

Related

Server doesn't enable my spigot plugin. (It doesn't even try)

I'm basically making a spigot plugin, for practice.
The server doesn't enable the server, no error in the console. It also no "INFO" for enabling the plugin.
This is my main class
package me.FarrosGaming.SpawnPillager;
import org.bukkit.plugin.java.JavaPlugin;
import me.FarrosGaming.SpawnPillager.commands.PillagerCommand;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
new PillagerCommand(this);
}
#Override
public void onDisable() {
}
}
This is my command class
package me.FarrosGaming.SpawnPillager.commands;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import me.FarrosGaming.SpawnPillager.Main;
public class PillagerCommand implements CommandExecutor {
private Main plugin;
public PillagerCommand(Main plugin) {
this.plugin = plugin;
plugin.getCommand("chase").setExecutor(this);
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Only players who can send this command.");
return true;
}
Player player = (Player) sender;
if (player.hasPermission("hello.use")) {
Location location = player.getLocation();
World world = player.getWorld();
for (int i = 0; i < 10; i++) {
world.spawnEntity(location, EntityType.CREEPER);
}
return true;
} else {
player.sendMessage("You do not have a permission to use this command");
}
return false;
}
}
this is my plugin.yml file
name: SpawnPillager
version: 1.0
author: FarrosGaming
description: blabla
main: me.FarrosGaming.SpawnPillager.Main
commands:
chase:
description: Spawn pillager in your location
usage: /chase
Literally, there are no spaces in the plugin.yml
I'm using the newest version of spigot.
make sure you are dropping your plugin's Jar in the right spot, i mean the right server's plugins folder, if you multiple and then reload/ restart your server,
I m telling this coz, me myself, have done this mistake too..

Detecting when a player leaves a projectile and then removing entity

I am building a 1.8.8 Bukkit/Spigot plugin that allows you to ride ender pearls and am stuck at detecting a dismount and removing the pearl. I have tried to catch the event but it doesn’t compile. I need a way to remove the pearl when there is a dismount. Thank you!
package damotheryeeter.general.enderpearlride.events;
import org.bukkit.entity.Player;
import static org.bukkit.Material.ENDER_PEARL;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.inventory.ItemStack;
public class EnderThrowEvent implements Listener {
#EventHandler
public void onThrow(final ProjectileLaunchEvent e) {
if (e.getEntityType().equals(EntityType.ENDER_PEARL)) {
if (!(e.getEntity().getShooter() instanceof Player)) return;
if (((Player) e.getEntity().getShooter()).hasPermission("enderpearlride.ride")) {
e.getEntity().setPassenger((Player) e.getEntity().getShooter());
if (((Player) e.getEntity().getShooter()).hasPermission("enderpearlride.infinite")) {
final Player p = (Player) e.getEntity().getShooter();
final ItemStack[] pearl = {new ItemStack(ENDER_PEARL, 1)};
p.getInventory().addItem(pearl);
}
}
}
}
The code for that is:
#EventHandler
public void onDismount(EntityDismountEvent e) {
if(e.getEntity().getEntityType().equals(EntityType.ENDER_PEARL)) {
e.getEntity().remove();
}
}

Error: Could not pass event PlayerJoinEvent to Plugin (BUKKIT)

I'm doing a test plugin, and when I log in, it doesn't tell me the login message, but it gives me an error. Here is the log: https://pastebin.com/SyBN5G2k
I looked up in internet but I can't found nothing that helps me.
Can someone help me i need it to make my server!
This the code of the PlayerJoinEvent event :
package com.Test.events;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import com.Test.main.MClass;
public class Enter implements Listener{
private MClass plugin;
public Enter(MClass plugin) {
this.plugin = plugin;
}
#EventHandler
public void onEnter(PlayerJoinEvent event) {
Player player = event.getPlayer();
Location spawn = new Location(player.getWorld(), -8, 64, -467.0, -90, 0);
player.teleport(spawn);
FileConfiguration config = plugin.getConfig();
String path = "config.welcome-message";
if(config.getString(path).equals("true")) {
String text = "Config.welcome-message-text";
player.sendMessage(config.getString(text));
}
}
}
And this my main class (called MClass)
package com.Test.main;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import com.Test.commands.CommandPotatoes;
import com.Test.commands.PrincipalCommand;
import com.Test.events.Enter;
public class MClass extends JavaPlugin{
public String configPath;
PluginDescriptionFile pdffile = getDescription();
//Declaration on variables thas include info of the version and the name
public String name = ChatColor.GOLD+""+ChatColor.BOLD+"["+pdffile.getName()+"] "+ChatColor.RESET;
public String version = pdffile.getVersion();
//Instruction on enable plugin
public void onEnable() {
//Mensaje de la consola que indica que el plugin ha sido activado
Bukkit.getConsoleSender().sendMessage(name+ChatColor.BLUE+"Sucesfully loaded (ver "+version+")");
registerCommands();
registerEvents();
registerConfig();
}
public void registerCommands() {
this.getCommand("potatoes").setExecutor(new CommandPotatoes(this));
this.getCommand("test").setExecutor(new PrincipalCommand(this));
}
public void registerEvents() {
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new Enter(this), this);
}
public void registerConfig() {
File config = new File(this.getDataFolder(),"config.yml");
configPath = config.getPath();
if(!config.exists()) {
this.getConfig().options().copyDefaults(true);
saveConfig();
}
}
}
Plz help i need it to make my server :(
This is what you are looking for:
Caused by: java.lang.NullPointerException
at com.Test.events.Enter.onEnter(Enter.java:27) ~[?:?]
Line #27 would be if(config.getString(path).equals("true"))
Check whether there is indeed a string at that path, meaning
config:
welcome-message: true
as a side note, you should use boolean types for truth values, not strings.

NPE on plugin.getConfig().set(... , ...); [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've a bug on my Spigot Plugin, a null pointer is return when i try to do /samrandom true/false. This is my code :
Main class:
package com.vandendaelen.simpleautomessage;
import java.io.File;
import java.util.List;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import com.vandendaelen.simpleautomessage.Commands.CommandSamRandom;
import com.vandendaelen.simpleautomessage.Commands.CommandSamTime;
public class SimpleAutoMessage extends JavaPlugin {
public static final String RANDOM_CONFIG ="Random enabled";
private int iMessages = 0;
#Override
public void onDisable() {
// TODO Auto-generated method stub
super.onDisable();
}
#Override
public void onEnable() {
System.out.println("Waw, an amazing plugin powered by LotuxPunk ! :-)");
this.getCommand("samtime").setExecutor(new CommandSamTime(this));
this.getCommand("samrandom").setExecutor(new CommandSamRandom(this, RANDOM_CONFIG));
createConfig();
this.getConfig().addDefault(RANDOM_CONFIG, false);
this.getConfig().options().copyDefaults(true);
saveConfig();
//Enable display of messages
if(getConfig().getBoolean("Enable")) {
if(getConfig().getBoolean(RANDOM_CONFIG)) {
messageRandomDisplayer();
} else {
messageDisplayer();
}
}
}
private void createConfig() {
try {
if (!getDataFolder().exists()) {
getDataFolder().mkdirs();
}
File file = new File(getDataFolder(), "config.yml");
if (!file.exists()) {
getLogger().info("Config.yml not found, creating!");
saveDefaultConfig();
} else {
getLogger().info("Config.yml found, loading!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
...
}
Command class :
package com.vandendaelen.simpleautomessage.Commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class CommandSamRandom implements CommandExecutor {
private String RANDOM_CONFIG;
private Plugin plugin;
public CommandSamRandom(Plugin pl, String r) {
pl = plugin;
RANDOM_CONFIG = r;
//System.out.println(plugin.getConfig().getBoolean(RANDOM_CONFIG));
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player p = (Player)sender;
if(args[0]!="") {
Boolean randomEnabled = Boolean.parseBoolean(args[0]);
if(p.hasPermission("simpleautomessage.setrandom")||p.isOp()) {
plugin.getConfig().set(RANDOM_CONFIG, randomEnabled);
if(randomEnabled) {
p.sendMessage("§2Random enabled");
} else {
p.sendMessage("§4Random disabled");
}
plugin.saveConfig();
plugin.reloadConfig();
return true;
}
}
return false;
}
}
Config file :
#Time between 2 messages (minutes)
Time: 15
#Auto-Messages !
Enable: true
#Broadcast randomly your messages
Random enabled: false
Messages:
- "A simple string"
- "Another string"
- "Don't forget to support/rate LotuxPunk on Curse/Bukkit website !"
Result :
[20:56:05 INFO]: LotuxPunk issued server command: /samrandom true
[20:56:05 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'samrandom' in plugin SimpleAutoMessage v0.5
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
...
Caused by: java.lang.NullPointerException
at com.vandendaelen.simpleautomessage.Commands.CommandSamRandom.onCommand(CommandSamRandom.java:26) ~[?:?]
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
... 15 more
Anyone can help me please ? :)
The line 26 is
plugin.getConfig().set(RANDOM_CONFIG, randomEnabled);
Your problem is in the Constructor:
private Plugin plugin;
public CommandSamRandom(Plugin pl, String r) {
pl = plugin;
}
You assign the value of your not yet initialized field pluginto the parameter pl insterad of the other way round.
It helps to explicitly use this.plugin when you try to access an instance field to make this more obvious.

Bukkit Java error: The method PlayerJoin(OnStartup) is undefined for the type OnStartup

So, I recently started learning Java and BukkitAPI. I make a config file, and I make a class for player events, but then I can't register the events in my main class. I get an error "The method PlayerJoin(OnStartup) is undefined for the type OnStartup" and the only fix is to make a method. Here is my code:
OnStartup(main class):
package ml.zonia.plugin;
import java.io.File;
import java.util.logging.Logger;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import ml.zonia.plugin.commands.Potion;
import ml.zonia.plugin.event.PlayerJoin;
public class OnStartup extends JavaPlugin implements Listener {
public void onEnable() {
registerEvents();
registerConfig();
PluginDescriptionFile pdfFile = getDescription();
Logger logger = getLogger();
getServer().getPluginManager().registerEvents(this, this);
getCommand("zonia").setExecutor(new Potion());
logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " has been enabled.");
}
public void registerEvents() {
PluginManager pm = getServer().getPluginManager();
//here is the error on PlayerJoin:The method PlayerJoin(OnStartup) is undefined for the type OnStartup
pm.registerEvents(PlayerJoin(this), this);
}
private void registerConfig() {
getConfig().options().copyDefaults(true);
saveConfig();
}
public void onDisable() {
PluginDescriptionFile pdfFile = getDescription();
Logger logger = getLogger();
logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " has been disabled.");
saveConfig();
}
}
Potion Class(Just in case):
package ml.zonia.plugin.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
public class Potion implements CommandExecutor, Listener {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (label.equalsIgnoreCase("zonia"))
;
if (!(sender instanceof Player)) {
sender.sendMessage("You must be in-game to execute this command.");
return false;
}
Player player = (Player) sender;
player.sendMessage(ChatColor.DARK_AQUA + "ZoniaCore, made by Patrick S.");
return true;
}
}
PlayerJoin:
package ml.zonia.plugin.event;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import ml.zonia.plugin.OnStartup;
public class PlayerJoin implements Listener {
private OnStartup plugin;
public PlayerJoin(OnStartup pl) {
plugin = pl;
}
#EventHandler
public void onJoin(PlayerJoinEvent pje) {
int PlayerSpeed;
PlayerSpeed = plugin.getConfig().getInt("PlayerSpeed");
if (!pje.getPlayer().hasPermission("zonia.effects.remove"))
;
pje.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, PlayerSpeed));
}
#EventHandler
public void onPlayerMove(PlayerMoveEvent pme) {
double SpawnX, SpawnY, SpawnZ;
SpawnX = plugin.getConfig().getDouble("SpawnX");
SpawnY = plugin.getConfig().getDouble("SpawnY");
SpawnZ = plugin.getConfig().getDouble("SpawnZ");
if ((int) pme.getPlayer().getLocation().getY() == 20) {
pme.getPlayer().teleport(new Location(Bukkit.getWorld("world"), SpawnX, SpawnY, SpawnZ));
}
}
}
In eclipse, the config yml looks like this:
################################
# #
# ZoniaCore-Hub Config #
# Version 1.0 #
# #
################################
#Sets the player's speed.
PlayerSpeed: 17
#sets X, Y, and Z of spawn.
SpawnX: -67.5
SpawnY: 156
SpawnZ: 4.5
#sets how much the player has to fall
#to be teleported back to spawn.
TeleportY: 50
But when it generates in the plugins folder under the plugin it generates the config like this, and I cant seem to make any changes to it.:
#
# #
# ZoniaCore-Hub Config #
# Version 1.0 #
# #
PlayerSpeed: 6
SpawnX: -67.5
SpawnY: 156
SpawnZ: 4.5
TeleportY: 50
You probably mean:
pm.registerEvents(new PlayerJoin(this), this);
I don't see a PlayerJoin function, only the constructor. BTW it would be a bad practice to start a function name with capital letter, unless it's the constructor.

Categories

Resources