Jump to content

[1.15.1] capability NullPointerException


transfarmer

Recommended Posts

Hello. I made a custom capability that should be attached to EntityPlayer. My provider class initializes an instance of Capabilty and sets its value to null and makes a LazyOptional instance of this capability:

    public static final Capability<ISoulWeapon> TYPE = null;
    private LazyOptional<ISoulWeapon> instance = LazyOptional.of(TYPE::getDefaultInstance);

I assume that this is correct because this is the only way in which I saw this done. However, the instance seems to be null. The game runs until a world is loaded, when it crashes, producing the following stacktrace:

java.lang.NullPointerException: Saving entity NBT
	at transfarmer.adventureitems.capabilities.Storage.writeNBT(Storage.java:14) ~[?:?] {re:classloading}
	at transfarmer.adventureitems.capabilities.Storage.writeNBT(Storage.java:10) ~[?:?] {re:classloading}
	at transfarmer.adventureitems.capabilities.Provider.serializeNBT(Provider.java:23) ~[?:?] {re:classloading,pl:capability_inject_definalize:A}
	at net.minecraftforge.common.capabilities.CapabilityDispatcher.serializeNBT(CapabilityDispatcher.java:127) ~[?:?] {re:classloading}
	at net.minecraftforge.common.capabilities.CapabilityProvider.serializeCaps(CapabilityProvider.java:86) ~[?:?] {re:classloading}
	at net.minecraft.entity.Entity.writeWithoutTypeId(Entity.java:1527) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at net.minecraft.server.integrated.IntegratedPlayerList.writePlayerData(IntegratedPlayerList.java:27) ~[?:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.server.management.PlayerList.saveAllPlayerData(PlayerList.java:631) ~[?:?] {re:classloading}
	at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:112) ~[?:?] {re:classloading,pl:runtimedistcleaner:A}
	at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:658) ~[?:?] {re:classloading,pl:accesstransformer:B}
	at java.lang.Thread.run(Thread.java:748) ~[?:1.8.0_232] {}

What did I do wrong?

My capability is available here.

Link to comment
Share on other sites

Well, you set it to null and made it final. It can't be anything else (unless you apply the @ObjectHolder annotation or use reflection).

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I read again the Forge documentation about capabilities. According to the it, the capability is null because it was not registered. Then I made it non-final and tried to properly register it during common setup. The NullPointerException does not occur anymore. However, my keybinding does not load anymore (I set its registration to occur during client setup by FMLClientSetupEvent as I was cleaning up my mod setup). Previously, it loaded but did not function. (It functioned as expected before I implemented the capability.) Should I open a new thread for that?

Also, the 1.15.x documentation mentions a provider hasCapability method. Is that a requirement in previous versions of Forge? It is not defined in ICapabilityProvider.java in v30.0.36.

Edited by transfarmer
Link to comment
Share on other sites

11 minutes ago, transfarmer said:

Is that a requirement in previous versions of Forge?

Yes. getCapability is pretty much the only thing that interface provides.

  • Thanks 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

The Forge documentation states the following:

Quote

The return type of getCapability will correspond to the type declared in the capability passed to the method. For the Item Handler capability, this is indeed IItemHandler.

However, the return type of getCapability is LazyOptional<T>, and I want to use the methods defined in my interface. How should I use getCapability?

Link to comment
Share on other sites

Yes. It should be LazyOptional<T>. Note that <T> here is still the type of the capability, so you'll get back a LazyOptional<IItemHandler>. Which you can then call ifPresent() on and pass in a lambda that gets executed if the capability is indeed present (non-null) or you can do something like OrElse(null) and null check (prefer using ifPresent) or use OrElseThrow().

  • Thanks 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

You need to attach capabilities to things you don't control. Like the player. Use the EntityJoinedWorldEvent for that.

  • Thanks 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

4 hours ago, diesieben07 said:

AttachCapabilitiesEvent

I could not remember if this was actually a thing.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I already have it:

@EventBusSubscriber(modid = Main.MODID, bus = EventBusSubscriber.Bus.MOD)
public class ModEventSubscriber {
    . . .
    @SubscribeEvent
    public static void onAttachCapabilities(AttachCapabilitiesEvent<Entity> event) {
        if (event.getObject() instanceof PlayerEntity) {
            event.addCapability(new ResourceLocation(Main.MODID, "type"), new Provider());
        }
    }
    . . .
}

Is something wrong with this code?

Edited by transfarmer
Link to comment
Share on other sites

Loading a world produces a NullPointerExceptionagain. The ICapability instance passed to writeNBT seems to be null:

Spoiler

java.lang.NullPointerException: Saving entity NBT
    at transfarmer.adventureitems.capability.SoulWeaponStorage.writeNBT(SoulWeaponStorage.java:14) ~[?:?] {re:classloading}
    at transfarmer.adventureitems.capability.SoulWeaponStorage.writeNBT(SoulWeaponStorage.java:10) ~[?:?] {re:classloading}
    at transfarmer.adventureitems.capability.SoulWeaponProvider.serializeNBT(SoulWeaponProvider.java:26) ~[?:?] {re:classloading}
    at net.minecraftforge.common.capabilities.CapabilityDispatcher.serializeNBT(CapabilityDispatcher.java:127) ~[?:?] {re:classloading}
    at net.minecraftforge.common.capabilities.CapabilityProvider.serializeCaps(CapabilityProvider.java:86) ~[?:?] {re:classloading}
    at net.minecraft.entity.Entity.writeWithoutTypeId(Entity.java:1358) ~[?:?] {re:classloading,pl:accesstransformer:B}
    at net.minecraft.server.integrated.IntegratedPlayerList.writePlayerData(SourceFile:24) ~[?:?] {re:classloading,pl:runtimedistcleaner:A}
    at net.minecraft.server.management.PlayerList.saveAllPlayerData(PlayerList.java:602) ~[?:?] {re:classloading}
    at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:106) ~[?:?] {re:classloading,pl:runtimedistcleaner:A}
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:634) ~[?:?] {re:classloading,pl:accesstransformer:B}
    at java.lang.Thread.run(Thread.java:748) ~[?:1.8.0_232] {}

 

Spoiler

public class SoulWeaponStorage implements IStorage<ISoulWeapon> {
    @Override
    public INBT writeNBT(Capability<ISoulWeapon> capability, ISoulWeapon instance, Direction side) {
        CompoundNBT tag = new CompoundNBT();
        tag.putString("adventureitems.weaponType", instance.getCurrentType().getName());
        return tag;
    }
    . . .
}

public class SoulWeaponProvider implements ICapabilitySerializable<INBT> {
    @CapabilityInject(ISoulWeapon.class)
    public static Capability<ISoulWeapon> TYPE;
    private LazyOptional<ISoulWeapon> instance = LazyOptional.of(TYPE::getDefaultInstance);
    . . .
}

 

Edited by transfarmer
Link to comment
Share on other sites

1 minute ago, diesieben07 said:

Why have you not shown this?

I apologize. The issue with writeNBT was that I was trying to use Object.toString() on a value that was null.The provider class is shown below.

Spoiler

public class SoulWeaponProvider implements ICapabilitySerializable<INBT> {
    @CapabilityInject(ISoulWeapon.class)
    public static Capability<ISoulWeapon> TYPE;
    private LazyOptional<ISoulWeapon> instance = LazyOptional.of(TYPE::getDefaultInstance);

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> capability, Direction side) {
        return capability == TYPE ? instance.cast() : LazyOptional.empty();
    }

    @Override
    public INBT serializeNBT() {
        return TYPE.getStorage().writeNBT(TYPE, instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional is empty")), null);
    }

    @Override
    public void deserializeNBT(INBT nbt) {
        TYPE.getStorage().readNBT(TYPE, instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional is empty")), null, nbt);
    }
}

 

 

6 minutes ago, diesieben07 said:

This makes no sense.

I agree. Does it have to be initialized? If so, then what should it be?

Link to comment
Share on other sites

Just now, diesieben07 said:

So your issue is fixed?

Yes.

 

4 minutes ago, diesieben07 said:

I misread, for some reason I read this to be in your storage class. Your code is fine.

Then could you explain to me what it does? I'm still not sure about why I need it. Is it a basic instance made for every object to which the capability is attached for NBT storage? Also, I think that my data are not saved after leaving and joining a world. Do I have to do it manually?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • They were already updated, and just to double check I even did a cleanup and fresh update from that same page. I'm quite sure drivers are not the problem here. 
    • i tried downloading the drivers but it says no AMD graphics hardware has been detected    
    • Update your AMD/ATI drivers - get the drivers from their website - do not update via system  
    • As the title says i keep on crashing on forge 1.20.1 even without any mods downloaded, i have the latest drivers (nvidia) and vanilla minecraft works perfectly fine for me logs: https://pastebin.com/5UR01yG9
    • Hello everyone, I'm making this post to seek help for my modded block, It's a special block called FrozenBlock supposed to take the place of an old block, then after a set amount of ticks, it's supposed to revert its Block State, Entity, data... to the old block like this :  The problem I have is that the system breaks when handling multi blocks (I tried some fix but none of them worked) :  The bug I have identified is that the function "setOldBlockFields" in the item's "setFrozenBlock" function gets called once for the 1st block of multiblock getting frozen (as it should), but gets called a second time BEFORE creating the first FrozenBlock with the data of the 1st block, hence giving the same data to the two FrozenBlock :   Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=head] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@73681674 BlockEntityData : id:"minecraft:bed",x:3,y:-60,z:-6} Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=3, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=2, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} here is the code inside my custom "freeze" item :    @Override     public @NotNull InteractionResult useOn(@NotNull UseOnContext pContext) {         if (!pContext.getLevel().isClientSide() && pContext.getHand() == InteractionHand.MAIN_HAND) {             BlockPos blockPos = pContext.getClickedPos();             BlockPos secondBlockPos = getMultiblockPos(blockPos, pContext.getLevel().getBlockState(blockPos));             if (secondBlockPos != null) {                 createFrozenBlock(pContext, secondBlockPos);             }             createFrozenBlock(pContext, blockPos);             return InteractionResult.SUCCESS;         }         return super.useOn(pContext);     }     public static void createFrozenBlock(UseOnContext pContext, BlockPos blockPos) {         BlockState oldState = pContext.getLevel().getBlockState(blockPos);         BlockEntity oldBlockEntity = oldState.hasBlockEntity() ? pContext.getLevel().getBlockEntity(blockPos) : null;         CompoundTag oldBlockEntityData = oldState.hasBlockEntity() ? oldBlockEntity.serializeNBT() : null;         if (oldBlockEntity != null) {             pContext.getLevel().removeBlockEntity(blockPos);         }         BlockState FrozenBlock = setFrozenBlock(oldState, oldBlockEntity, oldBlockEntityData);         pContext.getLevel().setBlockAndUpdate(blockPos, FrozenBlock);     }     public static BlockState setFrozenBlock(BlockState blockState, @Nullable BlockEntity blockEntity, @Nullable CompoundTag blockEntityData) {         BlockState FrozenBlock = BlockRegister.FROZEN_BLOCK.get().defaultBlockState();         ((FrozenBlock) FrozenBlock.getBlock()).setOldBlockFields(blockState, blockEntity, blockEntityData);         return FrozenBlock;     }  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.