I am having an issue with arrays. The full stack trace is:
java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.rangeCheck(Unknown Source) ~[?:1.7.0_79]
at java.util.ArrayList.get(Unknown Source) ~[?:1.7.0_79]
at xyz.lexium.brocubes.drops.DropDB.getRandomDrop(DropDB.java:17) ~[DropDB.class:?]
at xyz.lexium.brocubes.blocks.BroBlock.onBlockDestroyedByPlayer(BroBlock.java:33) ~[BroBlock.class:?]
at net.minecraft.client.multiplayer.PlayerControllerMP.onPlayerDestroyBlock(PlayerControllerMP.java:187) ~[PlayerControllerMP.class:?]
at net.minecraft.client.multiplayer.PlayerControllerMP.func_178891_a(PlayerControllerMP.java:68) ~[PlayerControllerMP.class:?]
at net.minecraft.client.multiplayer.PlayerControllerMP.func_180511_b(PlayerControllerMP.java:232) ~[PlayerControllerMP.class:?]
at net.minecraft.client.Minecraft.clickMouse(Minecraft.java:1519) ~[Minecraft.class:?]
at net.minecraft.client.Minecraft.runTick(Minecraft.java:2126) ~[Minecraft.class:?]
at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:1087) ~[Minecraft.class:?]
at net.minecraft.client.Minecraft.run(Minecraft.java:376) [Minecraft.class:?]
at net.minecraft.client.main.Main.main(Main.java:117) [Main.class:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.7.0_79]
at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) [launchwrapper-1.12.jar:?]
at net.minecraft.launchwrapper.Launch.main(Launch.java:28) [launchwrapper-1.12.jar:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.7.0_79]
at net.minecraftforge.gradle.GradleStartCommon.launch(Unknown Source) [start/:?]
at GradleStart.main(Unknown Source) [start/:?]
The code I use for this is:
DropBase drop = DropDB.getRandomDrop();
for (int i = 1; i < drop.getDrops().size() -1; i++) {
EntityItem item = new EntityItem(worldIn, pos.getX(), pos.getY() + 1, pos.getZ(), drop.getDrops().get(i));
System.out.println(i);
worldIn.spawnEntityInWorld(item);
This code calls DropDB and selects a random drop from a registered list. The list is perfectly fine. Here is the code for getDrop is:
public static DropBase getRandomDrop() {
Random rand = new Random();
int n = rand.nextInt(drops.size()) + 1;
System.out.println(n);
System.out.println(drops.size());
return drops.get(n);
}
This code causes this error. I have tired to look at the other questions around here. They have not worked.
Indices in Java are 0-based the valid values are 0 to size() - 1. When you generate a new random number you should not + 1 you want a range of 0 to size() -1.
I was having similar issues with an array. I believe it has to do with the for loop itself, quite not sure though, feel free to correct.
The equivalent of what solved my issue would be this :
Look at this part
for (int i = 1; i < drop.getDrops().size() -1; i++)
I would do this instead :
Int dropsSize = drop.getDrops().size() - 1; // just to keep it clean
// but you don't have to do this.
for (int **i = 0**; i < dropsSize ; i++) {
This is the first time I am using XPath, and I am trying to query a very basic example.
String xml = "<resp><status>good</status><msg>hi</msg></resp>";
XPathFactory xpathFactory = XPathFactory.newInstance();
javax.xml.xpath.XPath xpath = xpathFactory.newXPath();
InputSource source = new InputSource(new StringReader(xml));
String status = "";
try {
status = (String) xpath.evaluate("//resp/status", source,XPathConstants.STRING);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("status=" + status);
I receive the following exception:
javax.xml.transform.TransformerException: Unable to evaluate expression using this context at
com.sun.org.apache.xpath.internal.XPath.execute(Unknown Source) at
com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(Unknown Source)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown
Source) at Heandlers.HTTP.x(HTTP.java:74) at
Views.Main.main(Main.java:15) Caused by: java.lang.RuntimeException:
Unable to evaluate expression using this context at
com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(Unknown
Source) at
com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(Unknown
Source) ... 5 more
--------- java.lang.RuntimeException: Unable to evaluate expression using this context at
com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(Unknown
Source) at
com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(Unknown
Source) at com.sun.org.apache.xpath.internal.XPath.execute(Unknown
Source) at
com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(Unknown Source)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown
Source) at Heandlers.HTTP.x(HTTP.java:74) at
Views.Main.main(Main.java:15)
--------------- linked to ------------------ javax.xml.xpath.XPathExpressionException:
javax.xml.transform.TransformerException: Unable to evaluate
expression using this context at
com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown
Source) at Heandlers.HTTP.x(HTTP.java:74) at
Views.Main.main(Main.java:15) Caused by:
javax.xml.transform.TransformerException: Unable to evaluate
expression using this context at
com.sun.org.apache.xpath.internal.XPath.execute(Unknown Source) at
com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(Unknown Source)
... 3 more Caused by: java.lang.RuntimeException: Unable to evaluate
expression using this context at
com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(Unknown
Source) at
com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(Unknown
Source) ... 5 more status=
Any suggestions?
Sounds like you're using an invalid InputSource, e.g. org.w3c.css.sac.InputSource. Make sure you've imported org.xml.sax.InputSource.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Chatlet Created
Chatlet Thrown
Inside reply
5684dc24617149a601dea913 Yes, Please let me in.
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.teamchat.client.sdk.impl.TeamchatAPIImpl.invokeMethod(Unknown Source)
at com.teamchat.client.sdk.impl.TeamchatAPIImpl.onMsg(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector.onMsg(Unknown Source)
at com.teamchat.client.sdk.impl.SimpleEventsExecutor.notifyCallbackMessage(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamImpl.handleLine(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamImpl.fetchEventStream(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamImpl.fetchOnceAndReturnInterruptedStatus(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector.getEvents(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector.mainloop(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector.access$000(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at frontEnd.sendRequest.onReply(sendRequest.java:75)
... 16 more
I am currently working on task where I need to throw some message on reading null value from the database cell. But When I try to do so my code throws NullPointerException. I tried to handle it using try catch block but nothing helped me.
public String getCellData(String sql_query) throws Exception {
System.out.println("Inside getCellData");
String cell_data = "";
try{
JSONArray queried_data = (JSONArray)db_work.retrieveQueryRows(db_work.retrieveData(sql_query).toString());
for (int i = 0; i < queried_data.size(); i++) {
JSONArray queried_row=(JSONArray) queried_data.get(i);
cell_data = queried_row.get(0).toString();
}
}
catch(NullPointerException e)
{
cell_data="empty";
return cell_data;
}
return cell_data;
}
if(response.equals("Yes, Please let me in.")){
String gender = fetch_details.getCellData("select * from Group_Join where Room='"+room_id+"'");
System.out.println(gender);
String goal = fetch_details.getCellData("select * from Group_Join where Room='"+room_id+"'");
System.out.println(goal);
api.performPostInCurrentRoom(new TextChatlet("Sure, thanks. We will add you to the support group."));
if (goal.equals("empty")) {
if (gender.equals("empty")) {
System.out.println("Gender and Goal Both Empty");
PrimaryChatlet gender_goal_chatlet=new PrimaryChatlet();
gender_goal_chatlet.alias("GenderGoal");
Form gender_goal_form=api.objects().form();
gender_goal_form.addField(api.objects().select().name("Goal").label("Goal").addOption("Weight Loss").addOption("Weight Gain").addOption("Muscle Tone"));
gender_goal_form.addField(api.objects().select().name("Gender").label("Gender").addOption("Male").addOption("Female"));
gender_goal_chatlet.setReplyScreen(gender_goal_form);
api.performPostInCurrentRoom(gender_goal_chatlet);
}
It isn't recommended to catch a runtime exception (which your NullPointerException is).
Why don't you try to avoid it in the first place?
Something like:
if (queried_row.get(0).toString() != null)
cell_data = queried_row.get(0).toString();
else
cell_data = "empty";
or
cell_data = (queried_row.get(0).toString() != null) ? queried_row.get(0).toString() : "empty";
First, here is my function "setProduct" :
public void setProduct(String code, int qty,double price,int nbrProduct){
System.out.println("Code = "+code);
System.out.println("qty = "+qty);
System.out.println("price = "+price);
System.out.println("nbrProduct = "+nbrProduct);
this.Produit[nbrProduct][0] = code;
this.Produit[nbrProduct][1] = Integer.toString(qty);
this.Produit[nbrProduct][2] = price+" €";
And now where I call :
Commande_Final Commande = new Commande_Final();
Commande = Cmd;
String name = Commande.getName();
double prixUnit = Function.GetMagPrice(radar,Qtyradar)/Qtyradar;
System.out.println("j'affiche le radar : "+name);
System.out.println("j'affiche le Qtyradar : "+Qtyradar);
System.out.println("j'affiche le prix du radar : "+prixUnit+" €");
System.out.println("nbr de produit = "+nbr_de_Produit);
Commande.setProduit(name,Qtyradar,prixUnit,nbr_de_Produit);
My problem :
I get an error when I do in "setProduct" => this.Produit[nbrProduct][0] = code;
The error says "java.lang.NullPointerException", I guess its trying to put an empty value in "this.Produit[nbrProduct][0]" but the thing is when I do the "System.out.println("Code = "+code);" its show me the correct code and the same for all others attributs :/
EDIT :
Here is how I create my Produit attribut :
public String[][] Produit = new String[99][3];
EDIT 2 :
stack trace :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Commande_Final.setProduit(Commande_Final.java:33)
at ZDialogInfo.Confirmer(ZDialogInfo.java:449)
at ZDialogV2$29.actionPerformed(ZDialogV2.java:1037)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The code (sorry I leave in french, then you see the real name I use):
public void Confirmer(boolean LoginCheck,String Nom,ZDialogInfo zInfo,final String Langue, Commande_Final Cmd) throws IOException{
Commande_Final Commande = Cmd;
...
if (Qtyradar > 0){
/*
* PROBLEME ICI
*
* */
String name = Commande.showName();
double prixUnit = Function.GetMagPrice(radar,Qtyradar)/Qtyradar;
System.out.println("j'affiche le radar : "+name);
System.out.println("j'affiche le Qtyradar : "+Qtyradar);
System.out.println("j'affiche le prix du radar : "+prixUnit+" €");
System.out.println("nbr de produit = "+nbr_de_Produit);
/*ZDialogInfo.Confirmer(ZDialogInfo.java:449) => */
Commande.setProduit(name,Qtyradar,prixUnit,nbr_de_Produit);
nbr_de_Produit++;
System.out.println("nbr de produit = "+nbr_de_Produit);
JP_CNom.add(JL_CRadar);
JP_CNom.add(JL_CQtyRadar);
JP_CNom.add(JL_CPrixRadar);
if (RnbrItem >= 1) JP_CNom.add(RCompo1);
if (RnbrItem >= 2) JP_CNom.add(RCompo2);
if (RnbrItem >= 3) JP_CNom.add(RCompo3);
}
My public class Commande_Final
public class Commande_Final {
private String[][] Produit = new String[MAX_Produit][3];
/*
*
* [Nbr de Produit][0] = Code_Item
* [Nbr de Produit][1] = Qty_Cmdé
* [Nbr de Produit][2] = Prix_Unitaire
*
* */
public void setProduit(String code, int qty,double prix,int nbrProduit){
System.out.println(" ------------------- Dans setProduit ---------------------- ");
System.out.println("Code = "+code);
System.out.println("qty = "+qty);
System.out.println("prix = "+prix);
System.out.println("nbrProduit = "+nbrProduit);
/*at Commande_Final.setProduit(Commande_Final.java:33) =>*/ this.Produit[nbrProduit][0] = code;
this.Produit[nbrProduit][1] = Integer.toString(qty);
this.Produit[nbrProduit][2] = prix+"";
}
Most probably you haven't set up the array correctly.
A simplest example:
Foo[] foo = new Foo[10];
it is just making an array with 10 reference to Foo, however there is no actual Foo object those reference is pointing to. Hence it will cause NPE when you are trying to access foo[0].bar()
Similar,
Product[][] product = new Product[10][];
is going to give u an array of 10 reference pointing to Product[]. However there is no actual Product array object created. Therefore similar to the above example, you will get NPE if you do product[1][0], because product[1] is point to null, NPE is thrown because you want to access [0] of that null Product[] reference. You need to instantiate them explicitly.
Update:
With the extra code that OP quoted, I have tried to run that and there is no NPE from that piece of code.
It is most probably that, you have reassigned your produit (I would strongly recommend you follow Java's common naming convention) to null, or assigned produit[n] to null in some other code.
I would suggest a quick check on which one is null:
Add before your assignment:
System.out.println("produit null ? " + (produit == null));
System.out.println("produit[n] null ? " + (produit[nbrProduit] == null));
it should tell you which one is null, and give you hints where you may have incorrect updated the reference.
Problem
According to your stack trace, NPE is caused by this line:
this.Produit[nbrProduct][0] = code;
Apparently, you found out via console output that what is null here is this.Produit.
Possible Cause
Since you said you initialized Produit with the following line:
private String[][] Produit = new String[99][3];
then your NPE should not happen, unless you have reset the reference to null somewhere via some code like:
Commande.Produit = null;
Finding write accesses
If you're using Eclipse, there is a way to find every write access to your attribute:
click on your attribute Produit in your Commande_Final class, so that it is highlighted
go to Search > Write Access > Project
check if there is any other write access than your initialization
My guess is that this.Produit[nbrProduct] is null.
It can be initialized: this.Produit[nbrProduct] = new String[someSize];
Assigning null never causes a NPE, the issue must be your array has been not initialized.
The array is initialized when the object is created, so my guess is that array is re-assigned before the setProduct method is called. Check if this.Produit[nbrProduct] is not null when setProduct is called.
PS: Please, use Java conventions: method, attribute and variable names start with lowcase, class/interface names start with uppercase. In general try to use CamelCase (except constants, that should be LIKE_THIS_EXAMPLE)
When I am saving a List of objects by calling saveListOfPageChooserElement, it throws the below exception
Whereas, when I am saving a single instance by calling saveOrUpdate, then it works fine.
But to improve performance I want to save a List batch rather than single object at a time.
Can anyone suggest what's the problem with saving a whole list at once?
List<Abc> listabc = widgetCopyDAO
.fetchabcByPageId(id);
for (Abc abc: listabc ) {
abc.setLastUpdatedBy(null);
abc.setLastUpdatedOn(null);
abc.setCreatedBy(widgetCopyDTO.getUserName());
abc.setCreatedOn(new Date());
abc.setPageChooser(new PageChooser(chooser.getId()));
abc.setId(0l);
issuePageWidgetDAO.saveOrUpdate(abc);
}
// widgetCopyDAO.saveListOfPageChooserElement(listabc);
public void saveOrUpdate(Abc abc) {
if (abc.getId() == 0) {
Long id = (Long) this.getHibernateTemplate().save(
abc);
abc.setId(id);
} else {
this.getHibernateTemplate().update(abc);
}
}
public void saveListOfPageChooserElement(
List<Abc> listabc) {
this.getHibernateTemplate().saveOrUpdateAll(listabc);
}
The exception is
org.springframework.orm.hibernate3.HibernateSystemException: identifier of an instance of com.mct.model.Abc was altered from 138 to 0; nested exception is org.hibernate.HibernateException: identifier of an instance of com.mct.model.Abc was altered from 138 to 0
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:676)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1055)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1048)
at com.mct.dao.WidgetCopyDAO.fetchPageChooserWithImagesByChooser(WidgetCopyDAO.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor.invoke(ThrowsAdviceInterceptor.java:126)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:50)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:50)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy58.fetchPageChooserWithImagesByChooser(Unknown Source)
at com.mct.service.widgethelper.ChooserWidget.copyWidget(ChooserWidget.java:676)
at com.mct.service.widgethelper.ChooserWidget.copyAllWidgets(ChooserWidget.java:634)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown
You set ht Ids of all objects in the list:
abc.setId(0l);
And that's what causes the error.
You cannot change an auto-generated ID by your own.
Remove this line.
In hibernate You can't set Id (Autogenrated) manulally like below.
abc.setId(0l);
Remove this above line try again.
The problem appears to be this line:
abc.setId(0l);
You are clearing the ids of the entities you've loaded from the database.