java.lang.IndexOutOfBoundsException: Index: 5, Size: 5 - java

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++) {

Related

Nullpointer Error in groovy script while trying to add xpath assertion

I am getting an error as
java.lang.NullPointerException: Cannot invoke method getAssertionByName() on null object error at line: 5
however I am able to add xpath assertion in the test case.
As, I am new to groovy so want to know :-
What is the reason that I am getting this error.
How can I implement a code for select from current option in xpath assertion so that i can add xpath instead of printing some junk value(i have printed "hello" as of now).
log.info("Testing Start")
def project = context.testCase.testSuite.project
TSName = "ManagePostpayInsurance_1_0"
StepName = "getInsuranceDetails_FC_004"
project.getTestSuiteList().each {
if(it.name == TSName) {
TS = it.name
it.getTestCaseList().each {
TC =it.name
def asserting = project.getTestSuiteByName(TS).getTestCaseByName(TC).getTestStepByName(StepName).getAssertionByName("XPath Match")
log.info(asserting)
if (asserting instanceof com.eviware.soapui.impl.wsdl.teststeps.assertions.basic.XPathContainsAssertion){
project.getTestSuiteByName(TS).getTestCaseByName(TC).getTestStepByName(StepName).removeAssertion(asserting)
}
def assertion = project.getTestSuiteByName(TS).getTestCaseByName(TC)getTestStepByName(StepName).addAssertion("XPath Match")
assertion.path = "declare namespace cor='http://soa.o2.co.uk/coredata_1';\ndeclare namespace man='http://soa.o2.co.uk/managepostpayinsurancedata_1';\ndeclare namespace soapenv='http://schemas.xmlsoap.org/soap/envelope/';\n//man:getInsuranceDetails_1Response"
assertion.expectedContent = "hello"
}
}
}
log.info("Testing Over")
I have attached the error log below.
Mon Nov 27 17:04:12 IST 2017:ERROR:java.lang.NullPointerException: Cannot invoke method getAssertionByName() on null object
java.lang.NullPointerException: Cannot invoke method getAssertionByName() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:77)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:45)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:32)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at com.eviware.soapui.model.testsuite.Assertable$getAssertionByName.call(Unknown Source)
at Script10$_run_closure1_closure2.doCall(Script10.groovy:11)
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.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:909)
at groovy.lang.Closure.call(Closure.java:411)
at groovy.lang.Closure.call(Closure.java:427)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1325)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1297)
at org.codehaus.groovy.runtime.dgm$148.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:271)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at Script10$_run_closure1.doCall(Script10.groovy:9)
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.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:909)
at groovy.lang.Closure.call(Closure.java:411)
at groovy.lang.Closure.call(Closure.java:427)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1325)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1297)
at org.codehaus.groovy.runtime.dgm$148.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:271)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at Script10.run(Script10.groovy:5)
at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.run(SoapUIGroovyScriptEngine.java:90)
at com.eviware.soapui.impl.wsdl.teststeps.WsdlGroovyScriptTestStep.run(WsdlGroovyScriptTestStep.java:141)
at com.eviware.soapui.impl.wsdl.panels.teststeps.GroovyScriptStepDesktopPanel$RunAction$1.run(GroovyScriptStepDesktopPanel.java:250)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I'm badly stuck with the above issue, quick help is really appreciated!!!!
Thank you very much
Here you go:
Since you are going thru hierarchically, do not require to refer full chain of methods starting from project.
Instead, you could directly access the step objects once you browse to step level. This way, NPE can be avoided.
Here is the fixed script, see the inline relevant comment.
import com.eviware.soapui.impl.wsdl.teststeps.assertions.basic.XPathContainsAssertion
log.info("Testing Start")
def project = context.testCase.testSuite.project
def suiteName = "ManagePostpayInsurance_1_0"
def stepName = "getInsuranceDetails_FC_004"
project.testSuiteList.each { suite ->
if(suiteName == suite.name) {
suite.testCaseList.each { kase ->
kase.testStepList.each { step ->
if (stepName == step.name) {
//Note the change here, directly getting the object from step object
def asserting = step.getAssertionByName("XPath Match")
log.info(asserting)
if (asserting instanceof XPathContainsAssertion){
step.removeAssertion(asserting)
}
def assertion = step.addAssertion("XPath Match")
assertion.path = "declare namespace cor='http://soa.o2.co.uk/coredata_1';\ndeclare namespace man='http://soa.o2.co.uk/managepostpayinsurancedata_1';\ndeclare namespace soapenv='http://schemas.xmlsoap.org/soap/envelope/';\n//man:getInsuranceDetails_1Response"
assertion.expectedContent = "hello"
}
}
}
}
}
log.info 'Testing Over'

Java JComboBox ActionListener crash

I'm getting
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: -1
when I'm deleting last Item in JComboBox. Anyone knows why?
cb = new JComboBox<String>();
bComboDelete.addActionListener(this);
bComboDelete = new JButton("X"); //deletes item from CB
bComboAccept = new JButton("#");// add an item
ArrayList<String> names = new ArrayList<String>(); //get name, runs with sNumbers
ArrayList<String> sNumbers = new ArrayList<String>();//some String numbers ----> e.g. [[1, 2, 3],[4, 5, 6]]
ArrayList<Integer> numbers = new ArrayList<Integer>(); //array to temp hold numbers
//***ending code from ActionListener
else if(s == bComboAccept)
{
sNumbers.add(numbers.toString());
//System.out.println(sNumbers);
names.add(tName.getText());//tName is JTextField
//cb.addItem(tName.getText());
cb.addItem(new String(tName.getText()));
cb.setSelectedItem(new String(tName.getText()));
}
else if(s == bComboDelete)
{
int z = cb.getSelectedIndex();
//System.out.println(z);
names.remove(z);
//System.out.println("Names: "+names);
sNumbers.remove(z);
//System.out.println("sNumbers: "+sNumbers);
cb.removeItem(cb.getSelectedItem());
}
else if(s == cbLista)
{
System.out.println("cb Action listener!\n--------------");
Integer i = cb.getSelectedIndex();
tNames.setText(nazwy.get(i));
tNumbers.setText("");//also TextField
numbers.clear();
numbers=arrayStringToIntegerArrayList(sNumbers.get(i));
tNumbers.setText(numbers.toString().substring(1, numbers.toString().length()-1));
}
Rest of crash code:
Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: -1 at
java.util.ArrayList.elementData(Unknown Source) at
java.util.ArrayList.get(Unknown Source) at
Okno.actionPerformed(Okno.java:339) at
javax.swing.JComboBox.fireActionEvent(Unknown Source) at
javax.swing.JComboBox.contentsChanged(Unknown Source) at
javax.swing.AbstractListModel.fireContentsChanged(Unknown Source) at
javax.swing.DefaultComboBoxModel.setSelectedItem(Unknown Source) at
javax.swing.DefaultComboBoxModel.removeElementAt(Unknown Source) at
javax.swing.DefaultComboBoxModel.removeElement(Unknown Source) at
javax.swing.JComboBox.removeItem(Unknown Source) at
Okno.actionPerformed(Okno.java:328) 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$500(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)
Try adding the following modifications...
else if(s == bComboDelete)
{
int z = cb.getSelectedIndex();
// -1 means that no item is selected
if (z > -1) {
//System.out.println(z);
names.remove(z);
//System.out.println("Names: "+names);
sNumbers.remove(z);
//System.out.println("sNumbers: "+sNumbers);
cb.removeItem(cb.getSelectedItem());
}
}
else if(s == cbLista)
{
System.out.println("cb Action listener!\n--------------");
Integer i = cb.getSelectedIndex();
// -1 means that no item is selected
if (i > -1) {
tNames.setText(nazwy.get(i));
tNumbers.setText("");//also TextField
numbers.clear();
numbers=arrayStringToIntegerArrayList(sNumbers.get(i));
tNumbers.setText(numbers.toString().substring(1, numbers.toString().length()-1));
}
}
It seems I fixed this.
Now code is like this:
I'm too lazy to rename the var to eng. Please ignore System out.
so:
nazwy = names
oceny = numbers
sOceny = sNumbers
cbLista = cb
tNazwa = tNames
tOceny = tNumbers
//----
else if(s == bComboDelete)
{
Object o = cbLista.getSelectedItem();
int z = nazwy.indexOf(o);
if(z>-1)
{
sOceny.remove(z);
nazwy.remove(z);
cbLista.removeItemAt(z);
System.out.println("Oceny w bloku delete(if)"+oceny.toString());
}
System.out.println("Oceny w bloku delete(poza if)"+oceny.toString());
}
else if(s == cbLista)
{
Object o = cbLista.getSelectedItem();
int z = nazwy.indexOf(o);
if(z>-1)
{
tNazwa.setText(nazwy.get(z));
oceny.clear();
oceny=arrayStringToIntegerArrayList(sOceny.get(z));
tOceny.setText(oceny.toString().substring(1, oceny.toString().length()-1));
System.out.println("Oceny w bloku CB"+oceny.toString());
}
else
{
tNazwa.setText("");
tOceny.setText("");
oceny.clear();
}
}

NullPointerException that should not occur

I am sorry to post that in case it is just something stupid I am doing, but I hope there is some weird Java thing causing this that I am unaware of and can that will help others. Am I overlooking something here? Why the NPE?
Here is my code:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
int itemSoldCount = Integer.parseInt(afterAt[1]);
System.out.println("itemSoldCount: " + itemSoldCount);
ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];
int i = 2;
for (int k = 0; k < itemSoldCount; k++){
String waiType = afterAt[i];
System.out.println("ShopJInternalFrame.shopHolderWAIType.length: " + ShopJInternalFrame.shopHolderWAIType.length);
System.out.println("waiType: " + waiType);
System.out.println("k: " + k);
ShopJInternalFrame.shopHolderWAIType[k].setText(waiType); //line 530
Here is my output:
itemSoldCount: 2
ShopJInternalFrame.shopHolderWAIType.length: 2
waiType: A
k: 0
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.jayavon.game.client.MyCommandReceiver$8.run(MyCommandReceiver.java:530)
at java.awt.event.InvocationEvent.dispatch(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.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)
ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];
This allocates storage for the array, but not for any JLabel objects. The array contains all nulls at this point. When you reach
ShopJInternalFrame.shopHolderWAIType[k].setText(waiType);
shopHolderWAIType[k] is null.
ShopJInternalFrame.shopHolderWAIType[k] will be null because you have not allocated any memory for individual array member. So you need to do this before you use the array member.
ShopJInternalFrame.shopHolderWAIType[k] = new new JLabel();

Saving List of Objects Throws Hibernate Exception

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.

Null pointer exception when access index of a DefaultListModel

I have a list:
JList characterList = new JList(characterListModel);
characterListModel = new DefaultListModel();
String myCharacters[]={"Dean Winchester","Sam Winchester",
"Bobby Singer","Castiel"};
for (String myCharacter : myCharacters) {
((DefaultListModel) characterList.getModel()).addElement(myCharacter);
}
And I've written a method, in a seperate class, to remove a character at a selected index:
public void removeCharacter() {
DefaultListModel characterListModel = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterListModel();
JList characterList = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterList();
int idx = characterList.getSelectedIndex(); //<---line 62
int size = characterListModel.getSize();
characterListModel.remove(idx);
if (size == 0) {
//do nothing
} else {
if (idx == characterListModel.getSize()) {
idx--;
}
characterList.setSelectedIndex(idx);
characterList.ensureIndexIsVisible(idx);
}
}
However when I run it with my button, I get this stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.detica.LarpDB.Controller.Controller.removeCharacter(Controller.java:62)
at com.detica.LarpDB.view.PlayerContentPane$3.actionPerformed(PlayerContentPane.java:94)
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$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$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)
A lot of the issues I've seen googling this, stem from the line: DefaultListModel characterListModel = ....
And the issue they have is that their creating a new instance of the object, now I''m only new to this whole Java thing, but this shouldn't be an issue with me, as I've not made anythign new, I've just been specific about which object this is.
Please could someone help me untangle myself?
Those 2 lines can create a lot of problems:
DefaultListModel characterListModel = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterListModel();
JList characterList = ((PlayerContentPane) IViewManager.Util.getInstance()
.getMyContainerPane().getMyPlayerManagerPane().getContentPane())
.getCharacterList();
If any of the chained methods return null (for whatever reason) the line will throw a NullPointerException.
I suggest you break them down in several lines and check the value of each call to see where you get the null from.
EDIT
Just realised that line 62 is int idx = characterList.getSelectedIndex();. It means that characterList is null.
If it's failing on the line that you indicated is line 62, then the only object referenced on that line, and therefore the only thing that could be null, is characterList. This implies that your getCharacterList function is returning null. (If the error was inside the getSelectedIndex function, then you would have another line in your stack trace.)
As you didn't post the getCharacterList function, I can't say much more. But you should take a look at that function and see under what circumstances it could return null.

Categories