Jump to content

[1.7.10] ItemStack saving question


TheTrueForce

Recommended Posts

Hi,

 

I've made a TileEntity (for a machine), and I want to save the inventory and energy that are currently stored in the machine.

I have 4 inventory slots, 3 inputs, and 1 output, and a EnergyStorage object from CoFHCore.

I'm using this code to try and save all this:


private EnergyStorage Storage;

// slots 0-2 are the inputs, slot 3 is the output
private ItemStack[] inventory;

@Override
public void readFromNBT(NBTTagCompound nbt) {
	this.Storage.readFromNBT(nbt);
	this.inventory[0] = ItemStack.loadItemStackFromNBT(nbt);
	this.inventory[1] = ItemStack.loadItemStackFromNBT(nbt);
	this.inventory[2] = ItemStack.loadItemStackFromNBT(nbt);
	this.inventory[3] = ItemStack.loadItemStackFromNBT(nbt);
	super.readFromNBT(nbt);
}

@Override
public void writeToNBT(NBTTagCompound nbt) {
	// TODO: Figure out why the inventory isn't saving, and fix it.
	nbt = Storage.writeToNBT(nbt);
	nbt = inventory[0].writeToNBT(nbt);
	nbt = inventory[1].writeToNBT(nbt);
	nbt = inventory[2].writeToNBT(nbt);
	nbt = inventory[3].writeToNBT(nbt);
	super.writeToNBT(nbt);
}

The ItemStack array is initialized in the constructor with 4 elements.

 

This isn't saving the TE, and it's throwing a nullPointerException on line 108 (the one with "inventory[3].writeToNBT()"), because that slot is currently null (empty).

 

This is the error stacktrace:

[09:11:43] [server thread/ERROR] [FML]: A TileEntity type com.trueForce.mclTweaks.tileentity.TECompressor has throw an exception trying to write state. It will not persist. Report this to the mod author
java.lang.NullPointerException
at com.trueForce.mclTweaks.tileentity.TECompressor.writeToNBT(TECompressor.java:108) ~[TECompressor.class:?]
at net.minecraft.world.chunk.storage.AnvilChunkLoader.writeChunkToNBT(AnvilChunkLoader.java:395) [AnvilChunkLoader.class:?]
at net.minecraft.world.chunk.storage.AnvilChunkLoader.saveChunk(AnvilChunkLoader.java:204) [AnvilChunkLoader.class:?]
at net.minecraft.world.gen.ChunkProviderServer.safeSaveChunk(ChunkProviderServer.java:287) [ChunkProviderServer.class:?]
at net.minecraft.world.gen.ChunkProviderServer.saveChunks(ChunkProviderServer.java:340) [ChunkProviderServer.class:?]
at net.minecraft.world.WorldServer.saveAllChunks(WorldServer.java:863) [WorldServer.class:?]
at net.minecraft.server.MinecraftServer.saveAllWorlds(MinecraftServer.java:370) [MinecraftServer.class:?]
at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:113) [integratedServer.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:485) [MinecraftServer.class:?]
at net.minecraft.server.MinecraftServer$2.run(MinecraftServer.java:752) [MinecraftServer$2.class:?]

 

I suspect that my use of null to denote an empty ItemStack (that is, one that does not contain any items) is wrong.

Am I correct in this suspicion, and what is the correct way to do so?

And also, am I doing anything else wrong?

Link to comment
Share on other sites

You're writing every

ItemStack

to the same compound tag, so each slot is overwriting the previous one. You need to write a list tag containing a compound tag for each slot's

ItemStack

. Include the slot number in each compound tag, skip any slots with a

null

ItemStack

.

 

Look at how

TileEntityChest

saves and loads its contents.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

this is what i use for reading the inv nbt data

if (tagCompound.hasKey("Items"))
	{
		NBTTagList tagList = (NBTTagList) tagCompound.getTag("Items");
		this.inv = new ItemStack[4];

		for (int i = 0; i < tagList.tagCount(); ++i)
		{
			NBTTagCompound nbt = (NBTTagCompound) tagList.getCompoundTagAt(i);
			byte s = nbt.getByte("Slot");

			if (s >= 0 && s < this.inv.length)
			{
				this.inv[s] = ItemStack.loadItemStackFromNBT(nbt);
			}
		}
	}

 

and this is what i use for saving the inv data

NBTTagList tagList = new NBTTagList();
	for (int i = 0; i < this.inv.length; ++i)
	{
		if (this.inv[i] != null)
		{
			NBTTagCompound nbt = new NBTTagCompound();
			nbt.setByte("Slot", (byte) i);
			this.inv[i].writeToNBT(nbt);
			tagList.appendTag(nbt);
		}
	}
	tagCompound.setTag("Items", tagList);

Link to comment
Share on other sites

Choonster:

Thanks for that, I hadn't realized that was happening. I would've looked at how some MC TileEntity saved, but the decompiled code is hideously hard to read.

Also, the energy isn't saving. I'm using the writeToNBT() method that comes with EnergyStorage. Should I tag that with a slot number, or put it in a nested NBTTagCompound?

 

nexusrightsi:

Thanks for that code.

I think I understand how that works, so I'll try to write my own methods before just copy/pasting those ones.

 

shadowfacts:

Yes. I am initializing inventory[] with this line in the constructor:

inventory[] = new ItemStack[this.getSizeInventory()];

The getSizeInventory() method just returns 4, from a private constant.

 

 

EDIT: OK, I've altered the load/save code to:

@Override
public void readFromNBT(NBTTagCompound nbt) {
	System.out.println("Beginning Load");
	this.inventory = new ItemStack[iNV_SIZE];
	NBTTagList invTags = (NBTTagList) nbt.getTag("inventory");
	NBTTagCompound swapTag = new NBTTagCompound(); 
	byte slotNum = 0;
	for (byte i = 0; i>=INV_SIZE; i++) {
		swapTag = invTags.getCompoundTagAt(i);
		slotNum = swapTag.getByte("slot");
		if (slotNum >=0 && slotNum <= INV_SIZE);
		inventory[slotNum] = ItemStack.loadItemStackFromNBT(swapTag);
		System.out.println("loaded slot " + slotNum + " : " + swapTag);
	}
	this.Storage.readFromNBT(nbt);
	super.readFromNBT(nbt);
}

@Override
public void writeToNBT(NBTTagCompound nbt) {
	System.out.println("Beginning Save");
	// TODO: Figure out why the inventory isn't saving, and fix it.
	NBTTagList invTags = new NBTTagList();
	NBTTagCompound swapTag = new NBTTagCompound();
	for (byte i=0; i >= INV_SIZE; i++) {
		swapTag = new NBTTagCompound();
		swapTag.setByte("slot", i);
		inventory[i].writeToNBT(swapTag);
		invTags.appendTag(swapTag);
		System.out.println("saved slot " + i + " : " + swapTag);
	}
	Storage.writeToNBT(nbt);
	nbt.setTag("inventory", invTags);
	super.writeToNBT(nbt);
}

This no longer throws an NPE, but the "tells" in these routines aren't showing up in the console. This leads me to believe that the NBT read/write methods aren't being called, for some reason. What would cause that?

I can pastebin the entire class if it'll help.

Link to comment
Share on other sites

Choonster:

Thanks for that, I hadn't realized that was happening. I would've looked at how some MC TileEntity saved, but the decompiled code is hideously hard to read.

Also, the energy isn't saving. I'm using the writeToNBT() method that comes with EnergyStorage. Should I tag that with a slot number, or put it in a nested NBTTagCompound?

 

It should be okay to save the

EnergyStorage

in the root compound tag or a nested compound tag. It's not a slot, it doesn't need a slot number.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

Try getting the NBTTagList by doing:

NBTTagList list = nbt.getTagList("inventory", NBT.TAG_COMPOUND);

 

Just a thought...

 

Also, you're functions are not called when you enter the chunk?

If so, have you registered your TileEntity?

Then, place a breakpoint in the NBT functions, and debug it.

:P

I might be terribly wrong.. Like really, really wrong. But I'm just trying to help.

Link to comment
Share on other sites

Thanks, Ovikk, for pointing me to the breakpoints, and for that snippet of code.

It turns out that the methods were being called, but my loop condition was faulty and then the code NPE'd at a null ItemStack, so I put in a skipper. This is the working code:

@Override
public void readFromNBT(NBTTagCompound nbt) {
	//System.out.println("Beginning Load");
	this.inventory = new ItemStack[4];
	NBTTagList invTags = nbt.getTagList("inventory", NBT.TAG_COMPOUND);
	NBTTagCompound swapTag = new NBTTagCompound(); 
	byte slotNum = 0;
	for (byte i = 0; i <= 3; i++) {
		swapTag = invTags.getCompoundTagAt(i);
		slotNum = swapTag.getByte("slot");
		if (slotNum >=0 && slotNum <= 3);
		inventory[slotNum] = ItemStack.loadItemStackFromNBT(swapTag);
		//System.out.println("loaded slot " + slotNum + " : " + swapTag);
	}
	this.Storage.readFromNBT(nbt);
	super.readFromNBT(nbt);
}

@Override
public void writeToNBT(NBTTagCompound nbt) {
	//System.out.println("Beginning Save");
	NBTTagList invTags = new NBTTagList();
	NBTTagCompound swapTag = new NBTTagCompound();
	boolean check = false;
	for (byte i=0; i <= 3; i++) {
		swapTag = new NBTTagCompound();
		swapTag.setByte("slot", i);
		check = (inventory[i] != null);
		if (check) {
			inventory[i].writeToNBT(swapTag);
		}
		invTags.appendTag(swapTag);
		//System.out.println("saved slot " + i + " : " + swapTag);
	}
	Storage.writeToNBT(nbt);
	nbt.setTag("inventory", invTags);
	super.writeToNBT(nbt);
}

Thanks for your help. Now I need to make it actually process stuff, now that there's a point to doing so.

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

    • As a seasoned investor, I’ve learned that the financial world can be exciting and treacherous. My experiences with investments have taught me the importance of diligence and thorough research, particularly when dealing with newer and high-risk assets like Bitcoin. Unfortunately, my journey with Bitcoin was marred by a painful lesson in the form of a scam, which I hope to share to help others avoid similar pitfalls. My introduction to Bitcoin investing seemed promising. The allure of high returns and the buzz surrounding cryptocurrency were captivating. I was drawn to several Bitcoin investment platforms that promised substantial profits. These platforms presented themselves with professional websites, attractive promotions, and genuine testimonials. I was led to believe that these sites were reliable and that I was making a sound investment. However, this trust proved to be misplaced. The platform I initially invested in showcased fake success stories and substantial profits to entice investors. They used these fabricated examples to build credibility and persuade new investors like me to commit more funds. Their tactics were sophisticated; they knew exactly how to create an illusion of success and security. I, too, was lured by their promises and gradually invested a considerable amount of money, totaling 68,000 USD.The initial investments went smoothly. My account appeared to grow with impressive returns, and I felt a sense of validation in my investment strategy. But things took a drastic turn when I decided to make a more significant investment, believing that the returns would only get better. Once I deposited a substantial sum, the platform’s behavior changed abruptly. My account was frozen without warning, and I was faced with a barrage of demands for additional payments before I could access my funds or the supposed profits. The situation was both distressing and bewildering. I was met with excuses and obstructions at every turn. It became clear that I was dealing with a fraudulent company that had no intention of honoring its commitments. The realization that I had been deceived was crushing. The emotional and financial toll of the situation was overwhelming. Determined to recover my funds, I reached out to Trust Geeks Hack Expert, a service recommended by a trusted friend who had faced a similar ordeal. My initial skepticism was tempered by desperation and hope. Trust Geeks Hack Expert took immediate action. Their team worked tirelessly to investigate the fraudulent platform and recover my lost funds. Their dedication and expertise were evident throughout the process. In just a few weeks, Trust Geeks Hack Expert managed to successfully retrieve the full amount of 68,000 USD. Their assistance was thorough and professional, and they kept me informed every step of the way. Their efforts not only resulted in the recovery of my funds but also provided me with invaluable insights into how these scams operate. This. This experience has been a harsh lesson in the importance of conducting thorough research before investing in any platform, particularly in the cryptocurrency space. The allure of high returns can be overwhelming, but it’s crucial to approach such investments with caution. Verify the legitimacy of the platform, seek out reviews from reliable sources, and ensure that any investment opportunity has a track record of transparency and reliability. To anyone who finds themselves in a similar predicament, I cannot recommend Trust Geeks Hack Expert  enough. Their professionalism and commitment to recovering my funds were exemplary:: E>mail: trustgeekshackexpert {@} fastservice{.}com -----> Tele>gram : Trustgeekshackexpert, And also  What's>App   + 1-7-1-9-4-9-2-2-6-9-3
    • As a seasoned investor, I’ve learned that the financial world can be exciting and treacherous. My experiences with investments have taught me the importance of diligence and thorough research, particularly when dealing with newer and high-risk assets like Bitcoin. Unfortunately, my journey with Bitcoin was marred by a painful lesson in the form of a scam, which I hope to share to help others avoid similar pitfalls. My introduction to Bitcoin investing seemed promising. The allure of high returns and the buzz surrounding cryptocurrency were captivating. I was drawn to several Bitcoin investment platforms that promised substantial profits. These platforms presented themselves with professional websites, attractive promotions, and genuine testimonials. I was led to believe that these sites were reliable and that I was making a sound investment. However, this trust proved to be misplaced. The platform I initially invested in showcased fake success stories and substantial profits to entice investors. They used these fabricated examples to build credibility and persuade new investors like me to commit more funds. Their tactics were sophisticated; they knew exactly how to create an illusion of success and security. I, too, was lured by their promises and gradually invested a considerable amount of money, totaling 68,000 USD.The initial investments went smoothly. My account appeared to grow with impressive returns, and I felt a sense of validation in my investment strategy. But things took a drastic turn when I decided to make a more significant investment, believing that the returns would only get better. Once I deposited a substantial sum, the platform’s behavior changed abruptly. My account was frozen without warning, and I was faced with a barrage of demands for additional payments before I could access my funds or the supposed profits. The situation was both distressing and bewildering. I was met with excuses and obstructions at every turn. It became clear that I was dealing with a fraudulent company that had no intention of honoring its commitments. The realization that I had been deceived was crushing. The emotional and financial toll of the situation was overwhelming. Determined to recover my funds, I reached out to Trust Geeks Hack Expert, a service recommended by a trusted friend who had faced a similar ordeal. My initial skepticism was tempered by desperation and hope. Trust Geeks Hack Expert took immediate action. Their team worked tirelessly to investigate the fraudulent platform and recover my lost funds. Their dedication and expertise were evident throughout the process. In just a few weeks, Trust Geeks Hack Expert managed to successfully retrieve the full amount of 68,000 USD. Their assistance was thorough and professional, and they kept me informed every step of the way. Their efforts not only resulted in the recovery of my funds but also provided me with invaluable insights into how these scams operate. This. This experience has been a harsh lesson in the importance of conducting thorough research before investing in any platform, particularly in the cryptocurrency space. The allure of high returns can be overwhelming, but it’s crucial to approach such investments with caution. Verify the legitimacy of the platform, seek out reviews from reliable sources, and ensure that any investment opportunity has a track record of transparency and reliability. To anyone who finds themselves in a similar predicament, I cannot recommend Trust Geeks Hack Expert  enough. Their professionalism and commitment to recovering my funds were exemplary:: E>mail: trustgeekshackexpert{@}fastservice{.}com -----> Tele>gram : Trustgeekshackexpert, And also  What's>App   + 1-7-1-9-4-9-2-2-6-9-3
    • I've been playing it for only 1 day and it doesn't want to go into the game anymore. I've tried reinstalling the game and repairing the game files (on curseforge) but it still doesn't work. Whenever i try to click on the Singleplayer icon, it just flickers into the world creation page and flickers back 
    • https://gist.github.com/RealMangoBot/03ce10d60ce10f126dcf2c033c3a4f46  
  • Topics

×
×
  • Create New...

Important Information

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