Jump to content

[Solved][1.14.4] Capability NullPointerException


Zorochase

Recommended Posts

In my capability's Provider class, I set JUICED_ITEM_CAPABILITY to null.

This caused the NullPointerException, which I half expected, but only half

because that was how it was done for CapabilityEnergy, and I'm not sure

why. I've tried making it final, and I've tried leaving it unassigned, but neither

worked. I'm relatively new to the capability system and I clearly still don't

understand it in full. I've read through this topic in full, as well as the docs,

but nothing I read lead me to any other possible fix.

 

Here's my capability's provider class:

package zorochase.oneirocraft.capability;

import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;

public class JuicedItemProvider implements ICapabilitySerializable<INBT> {

    @CapabilityInject(IJuicedItem.class)
    public static Capability<IJuicedItem> JUICED_ITEM_CAPABILITY = null;
    private LazyOptional<IJuicedItem> instance = LazyOptional.of(JUICED_ITEM_CAPABILITY::getDefaultInstance);

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

    @Override
    public INBT serializeNBT() {
        return JUICED_ITEM_CAPABILITY.getStorage().writeNBT(JUICED_ITEM_CAPABILITY, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null);
    }

    @Override
    public void deserializeNBT(INBT nbt) {
        JUICED_ITEM_CAPABILITY.getStorage().readNBT(JUICED_ITEM_CAPABILITY, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null, nbt);
    }
}

 

I tried attaching the capability to a custom sword like so:

@Override
public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
    return new JuicedItemProvider();
}

 

I also registered the capability in my main mod class like so:

@SubscribeEvent
public static void onCommonSetup(FMLCommonSetupEvent event) {
    CapabilityManager.INSTANCE.register(IJuicedItem.class, new JuicedItemStorage(), JuicedItemImpl::new);
}

 

Here is the full crash report, if necessary.

If I do get any help, I'd really appreciate it.

Edited by Zorochase
Link to comment
Share on other sites

I discovered with my mod that due to the order of class loading (item registration depending on the ItemGroup from my main class) my initCapabilities method was being called before my capability instance was set, so it was attempting to call null.getDefaultInstance and throwing the error.

I resolved the issue by wrapping it in an additional supplier, so the capability was definitely set by the time it was used.

  • Like 1
Link to comment
Share on other sites

2 hours ago, Alpvax said:

I discovered with my mod that due to the order of class loading (item registration depending on the ItemGroup from my main class) my initCapabilities method was being called before my capability instance was set, so it was attempting to call null.getDefaultInstance and throwing the error.

I resolved the issue by wrapping it in an additional supplier, so the capability was definitely set by the time it was used.

Thanks for your response. I understand what you mean, but I couldn't quite figure out how to wrap it correctly. Would you be able to show me an example of how you did it?

Link to comment
Share on other sites

class Provider implements ICapabilityProvider {
    private Supplier<IMultitool> multitoolSup;

    Provider() {
      this(() -> Capabilities.MULTITOOL_CAPABILITY.getDefaultInstance());
    }
    Provider(Supplier<IMultitool> sup) {
      multitoolSup = sup;
    }

    private LazyOptional<IMultitool> capability = LazyOptional.of(() -> multitoolSup.get());

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

I had the advantage that my capability currently just acts as a flag, so I don't care about storing it for later use (i.e. I can just create a new instance every time with no issues).

You will probably want to save the value of `supplier.get()` if you interact with it outside of the LazyOptional.

Link to comment
Share on other sites

1 hour ago, Alpvax said:

class Provider implements ICapabilityProvider {
    private Supplier<IMultitool> multitoolSup;

    Provider() {
      this(() -> Capabilities.MULTITOOL_CAPABILITY.getDefaultInstance());
    }
    Provider(Supplier<IMultitool> sup) {
      multitoolSup = sup;
    }

    private LazyOptional<IMultitool> capability = LazyOptional.of(() -> multitoolSup.get());

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

I had the advantage that my capability currently just acts as a flag, so I don't care about storing it for later use (i.e. I can just create a new instance every time with no issues).

You will probably want to save the value of `supplier.get()` if you interact with it outside of the LazyOptional.

Alright, so applying your suggestion to my code did fix the error. However, there's another problem, and I'm not sure exactly what's causing it. It could be an issue with my capability's storage class, it could be that I'm not attaching the capability properly, or something else, but when I went to check my custom sword in-game, instead of printing the amount of "juice" it was supposed to store (juice is just another word for energy; it's just an int value) in the sword's tooltip, it just printed this: https://imgur.com/a/vOUhiDo

 

Here's my updated Provider class, in case that could have an effect on the above issue:

package zorochase.oneirocraft.capability;

import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.LazyOptional;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.Supplier;

public class JuicedItemProvider implements ICapabilityProvider {

    private Supplier<IJuicedItem> juicedItemSupplier;

    @CapabilityInject(IJuicedItem.class)
    public static Capability<IJuicedItem> JUICED_ITEM_CAPABILITY = null;

    public JuicedItemProvider() {
        this(() -> JUICED_ITEM_CAPABILITY.getDefaultInstance());
    }
    JuicedItemProvider(Supplier<IJuicedItem> sup) {
        this.juicedItemSupplier = sup;
    }

    private LazyOptional<IJuicedItem> capability = LazyOptional.of(() -> juicedItemSupplier.get());

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

}

 

Here's the storage class:

package zorochase.oneirocraft.capability;

import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;

import javax.annotation.Nullable;

public class JuicedItemStorage implements Capability.IStorage<IJuicedItem> {

    @Nullable
    @Override
    public INBT writeNBT(Capability<IJuicedItem> capability, IJuicedItem instance, Direction side) {
        CompoundNBT tag = new CompoundNBT();
        tag.putInt("juice", instance.getJuice());
        tag.putInt("maxJuiceTransferable", instance.getMaxJuiceTransferable());
        tag.putBoolean("empowered", instance.getIsEmpowered());
        return tag;
    }

    @Override
    public void readNBT(Capability<IJuicedItem> capability, IJuicedItem instance, Direction side, INBT nbt) {
        CompoundNBT tag = (CompoundNBT) nbt;
        instance.setJuice(tag.getInt("juice"));
        instance.setJuiceTransferLimit(tag.getInt("maxJuiceTransferable"));
        instance.setEmpowered(tag.getBoolean("empowered"));
    }
}

 

Here's how I'm printing the sword's "juice":

    @Override
    public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {
        tooltip.add(
                new TranslationTextComponent(
                        String.valueOf(
                                stack.getCapability(JuicedItemProvider.JUICED_ITEM_CAPABILITY).map(IJuicedItem::getJuice)
                        )
                ).applyTextStyle(TextFormatting.AQUA)
        );
    }

 

And here's what I did to attach it in my main class:

    @SubscribeEvent
    public static void onAttachCapabilities(AttachCapabilitiesEvent<ItemStack> event) {
        Item item = event.getObject().getItem();
        if (item instanceof DreamsteelSwordItem) {
            event.addCapability(new ResourceLocation(Oneirocraft.MOD_ID, "juiceditem"), new JuicedItemProvider());
        }
    }

 

Again, I really do appreciate your help. I apologize for requesting it continually, it's only because I'm having a hard time wrapping my head around this concept.

Link to comment
Share on other sites

After messing with the code a little more, (I think) I figured out I wasn't supposed to use .map to access the getJuice method. However, I tried a few variations of the following code, and it only, funny enough, produced another NullPointerException. Here's what I last tried:

    @Override
    public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {
        if (stack.getCapability(JuicedItemProvider.JUICED_ITEM_CAPABILITY).isPresent()) {
            stack.getCapability(JuicedItemProvider.JUICED_ITEM_CAPABILITY).ifPresent(juicedItem -> {
                int storedJuice = juicedItem.getJuice();
                tooltip.add(new TranslationTextComponent(String.valueOf(storedJuice)).applyTextStyle(TextFormatting.AQUA));
            });
        }
    }

 

I'm pretty sure there's no reason for me to check isPresent first. I left that out, produced the same error. I moved tooltip.add outside the lambda and made storedJuice an AtomicInteger, same error. I'm still using the same updated provider from the above reply. Here's the new error: https://pastebin.com/LJkhRes3

Link to comment
Share on other sites

18 hours ago, Zorochase said:

@SubscribeEvent
public static void onAttachCapabilities(AttachCapabilitiesEvent<ItemStack> event) {
    Item item = event.getObject().getItem();
    if (item instanceof DreamsteelSwordItem) {
        event.addCapability(new ResourceLocation(Oneirocraft.MOD_ID, "juiceditem"), new JuicedItemProvider());
    }
}

 

This is not how you should add capabilities to your own items, you should override IForgeItem#initCapabilities: 

@Nullable
@Override
public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
    return new IMultitool.Provider();
}

I can't really tell from the snippets you have posted, do you have a git repository?

Use your IDE to set breakpoints to try and find what is actually null when that function is called.

Link to comment
Share on other sites

13 hours ago, Alpvax said:

I can't really tell from the snippets you have posted, do you have a git repository?

My project was a bit messy, so I didn't have one. I cleaned it up a bit and made one, here's the link: https://github.com/Zorochase/Oneirocraft

 

13 hours ago, Alpvax said:

Use your IDE to set breakpoints to try and find what is actually null when that function is called.

I found out that the same issue from before wasn't totally fixed; wrapping the provider in a supplier only worked for initCapabilities (which I actually always had, I just added attachCapabilities later on because I wasn't sure whether it was necessary). That didn't actually ensure that the capability was set before the sword's other methods (I.E. addInformation) were called.

 

 

EDIT: As of this edit, the code you see on Github now correctly prints the amount of juice stored in the custom sword... but it doesn't update when I kill an entity, even though it should. It only updates when you leave the world and come back. This is the only known issue now.

Edited by Zorochase
Link to comment
Share on other sites

1 hour ago, Alpvax said:

Sounds like you need to sync the changes to the client when it changes.

I thought so, but I don't know how... been looking around for ways to do that but I haven't found anything specific to my situation, just for PlayerEntities.

 

EDIT: Nevermind, I've got myself on the right path now. Once again, thank you so much for your help. It will take me time to fully understand all the concepts I've come across but I know where to take it from here.

Edited by Zorochase
  • Like 1
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



×
×
  • Create New...

Important Information

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