I get the following error, when puting an element in the ehcache. Does anyone have any idea why this error occures?
Thank you in advance.
This is put method:
#SuppressWarnings("unchecked")
#Override
public void putActivity(Activity activity) {
// put activity itself
Serializable activityKey = KEY_PREFIX_ACTIVITY + activity.getId();
final Element activityElement = new Element(activityKey, activity);
getCache().put(activityElement);
// add activity to the list of user
ArrayList<Activity> activities = null;
Serializable userKey = KEY_PREFIX_USER_ACTIVITIES + activity.getExecutingUserId();
Element userActivities = getCache().get(userKey);
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = (ArrayList<Activity>) userActivities.getObjectValue();
}
activities.add(activity);
getCache().put(userActivities);
}
and here is the corresponding erorr:
Mrz 05, 2016 11:07:40 AM net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask call
Schwerwiegend: Disk Write of u-1 failed:
net.sf.ehcache.CacheException: Failed to serialize element due to ConcurrentModificationException. This is frequently the result of inappropriately sharing thread unsafe object (eg. ArrayList, HashMap, etc) between threads
at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:405)
at net.sf.ehcache.store.disk.DiskStorageFactory.write(DiskStorageFactory.java:385)
at net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask.call(DiskStorageFactory.java:477)
at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1071)
at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1055)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.util.ConcurrentModificationException
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor33.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
at net.sf.ehcache.Element.writeObject(Element.java:875)
at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at net.sf.ehcache.util.MemoryEfficientByteArrayOutputStream.serialize(MemoryEfficientByteArrayOutputStream.java:97)
at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:403)
... 10 more
and here more details from ehcache source code:
private MemoryEfficientByteArrayOutputStream [More ...] serializeElement(Element element) throws IOException {
// A ConcurrentModificationException can occur because Java's serialization
// mechanism is not threadsafe and POJOs are seldom implemented in a threadsafe way.
// e.g. we are serializing an ArrayList field while another thread somewhere in the application is appending to it.
try {
return MemoryEfficientByteArrayOutputStream.serialize(element);
} catch (ConcurrentModificationException e) {
throw new CacheException("Failed to serialize element due to ConcurrentModificationException. " +
"This is frequently the result of inappropriately sharing thread unsafe object " +
"(eg. ArrayList, HashMap, etc) between threads", e);
}
}
You are updating an object while it's been serialized (ehcache try to save it to disk). You should store in a cache only an immutable object.
In your case, don't try to reuse the ArrayList, create a new one:
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = new ArrayList<Activity>((List) userActivities.getObjectValue());
}
Instead of an ArrayList, you can instanciate a CopyOnWriteArrayList.
Related
I have 2D Arralist of Object and i want to sort it upon first column which contains LocalDate
i used this code to sort it
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
formatter = formatter.withLocale( Locale.US );
ArrayList<ArrayList<Object>> cusKashf = new ArrayList<ArrayList<Object>>();
cusKashf.addAll(new ReadBillDeateals().readSell(textField_4.getText()));
Collections.sort(cusKashf , new Comparator<ArrayList<Object>>() {
#Override
public int compare(ArrayList<Object> entry1, ArrayList<Object> entry2) {
return ((LocalDate.parse(entry1.get(0).toString(), formatter)).compareTo((LocalDate.parse(entry2.get(0).toString(), formatter))));
}
});
the problem is this code make an exception, i wonder where's the mistake in me code
this is the exception report
java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at reports.Kashf$7$1.compare(Kashf.java:327)
at reports.Kashf$7$1.compare(Kashf.java:1)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.ArrayList.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at reports.Kashf$7.actionPerformed(Kashf.java:324)
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$Actions.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(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.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
In your cusKashf List check if the sublist is not empty.
#Override
public int compare(ArrayList<Object> entry1, ArrayList<Object> entry2) {
if(Objects.isNull(entry1) || entry1.isEmpty()) return -1;
if(Objects.isNull(entry2) || entry2.isEmpty()) return -1;
return ((LocalDate.parse(entry1.get(0).toString(), formatter)).compareTo((LocalDate.parse(entry2.get(0).toString(), formatter))));
}
One of the lists you are trying to compare are empty, try surrounding by a try and catch or check if a list is empty before getting item 0.
So this is my first time posting, please be gentle :3
General overview:
My goal is to be able to give my program a XSD file, then the program generates a bean, generates a nice GUI using reflection on the bean, then I can enter appropriate values into the textfields and then the program updates the bean with the values and finally marshalls the bean into a nice XML.
It's coming along pretty good, but yesterday I stumbled over an error that I can't figure out..
StackTrace
java.lang.ClassNotFoundException: X.Y.Z.BEAN_FILE_WITHOUT_.JAVA
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at X.Y.Z.GenerateXMLService.generateBean(GenerateXMLService.java:101)
at X.Y.Z.view.Gui$1.handle(Gui.java:56)
at X.Y.Z.view.Gui$1.handle(Gui.java:1)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1800(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(Unknown Source)
at com.sun.glass.ui.win.WinApplication$4$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
generateBean
public Class generateBean(File xsd) {
String finalDir = System.getProperty("user.dir") + "/src/main/java";
String xsdDir = xsd.getParentFile().getAbsolutePath();
try {
Process p = Runtime.getRuntime().exec(
"cmd /c cd " + xsdDir + " && xjc -d " + finalDir
+ " -p PACKAGE_PATH_GOES_HERE " + xsd.getName().toString());
p.waitFor();
} catch (IOException | InterruptedException e) {
Gui.errorPopUp(e);
}
/**
* Get the newly created files and put them in an array
*/
File[] fList = new File[2];
fList = new File("DIRECTORY_PATH_GOES_HERE").listFiles();
/**
* Get the file that isn't Objectfactory.java ---> that's the bean
*/
for (File file : fList) {
if (!"ObjectFactory.java".equals(file.getName())) {
String beanName = file.getName();
String beanBinaryName = "PACKAGE_PATH_GOES_HERE"
+ beanName.substring(0, beanName.length() - 5);
Class beanClass = null;
try {
beanClass = Class.forName(beanBinaryName); //this is line 101
return beanClass;
} catch (ClassNotFoundException e) {
Gui.errorPopUp(e);
}
}
}
return null;
}
So I checked first if the beanBinaryName is correct, and I think it is. It has the following format:
com.foo.foo.some.more.foo.beanbag.bean
Then I started googling with the error message and stumbled accross this post:
Link to the blog
But to be honest I didn't really understand what he was trying to explain. The stacktrace looks similar, but I just started with java a few months ago and still consider myself a newbie. Do you have any advice what the error might be? Thank in advance!
EDIT / SOLUTION:
My first mistake was trying to use class.forName() on a .java file. This only works with compiled files, e.g. .class.
After I fixed that i was still getting error messages, but after playing around with the URLClassLoader it worked :D I renamed and refactored this method compared to the method at the top, so in this one we really only get the class, while in my first example I also generate the .java files. I now do this in a seperate method to keep things organized.
public Class getClassFromBean() {
File[] fList = new File[3];
fList = new File("foo/beanbag").listFiles();
Class beanClass = null;
for (File file : fList) {
String lastSix = file.getName().toString().substring(file.getName().length() - 6);
if (".class".equals(lastSix)) {
String beanBinaryName = "foo.beanbag."
+ file.getName().toString().substring(0, file.getName().toString().length() - 6);
try {
File root = new File(System.getProperty("user.dir") + "/src/main/java");
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI()
.toURL() });
beanClass = Class.forName(beanBinaryName, true, classLoader);
} catch (ClassNotFoundException | MalformedURLException e) {
Gui.errorPopUp(e);
}
return beanClass;
}
}
return beanClass;
}
Method Class.forName() works only for compiled classes i.e. for files with extension '.class'. You cannot just put '.java' file to your classpath.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have this code, which creates a textfield and a button to let the user search for data in an array:
//Creates a form to search data, list for it and buttons to sort the list.
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
final TextField searchTextField;
searchTextField = new TextField ();
rightPanel.add(searchTextField);
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
JButton searchConfirmButton = new JButton("Search");
rightPanel.add(searchConfirmButton);
searchConfirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try {
search = searchTextField.getText();
int index = Arrays.asList(data).indexOf(search);
for (String result : data) {
if (result.contains(search)) {
System.out.println(result);
System.out.println(index);
}
}
} catch (NullPointerException e1) {
}
}
});
But whenever I search for the data, whether it exists or not, the program returns me an nullpointerexception with the following content:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at program.Program$4$1.actionPerformed(Program.java:233)
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)
In this case, row 233 contains this line if (result.contains(search)) {
data looks like an array type that can hold data values or null pointers. You should try:
System.out.println("Found index: " + index);
for (String result : data) {
if (result != null && result.contains(search)) {
System.out.println("Found result: " + result);
}
//If you are still confused than the right else here will help.
}
If, for example, you split a string with two spaces in a row by space, then depending on your function parameters to split(), you can end up with an empty string in that location and you need to skip it effectively.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
At first there was an issue removing an element in an arraylist if it was the only one on the list but now there is an exception issue when deleting the last position of the arraylist. What is the best way to deal with this?
edit: Looking back, checking if it is the last element and putting in a dummy element to hold the only spot would work.
the code:
public void deleteCustomer(){
String id = null;
boolean c = false; //true if id is found
int remember = 0; //Remembers the deleted index
id = JOptionPane.showInputDialog(null,"input the if of whome you want to delete",
"input id", JOptionPane.PLAIN_MESSAGE);
int id2 = Integer.parseInt(id); //new int id.
for(int i = 0; i < customers.size(); i++){
if(id2 == customers.get(i).getID()){
if(customers.size() == 1){
System.out.println("test one person");
customers.get(i).setDate(null);
customers.get(i).setID(0);
customers.get(i).setName(null);
customers.get(i).setPeople(0);
}
else{
customers.remove(i);
}
c = true;
remember = i;
if(c == true)
break;
}
}
if(c == true){
int i1 = JOptionPane.showConfirmDialog(null,"the customer "
+ customers.get(remember).getName() + " has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
}
else{
int i1 = JOptionPane.showConfirmDialog(null,"the customer could not be found," +
" please check your id",
"input people", JOptionPane.PLAIN_MESSAGE);
}
}
the error
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MainFrame.deleteCustomer(MainFrame.java:360)
at MainFrame$4.actionPerformed(MainFrame.java:170)
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)
Don't remove elements from a collection while iterating over it with a for loop. Use an iterator instead which in most cases implements the remove method.
Iterator<Customer> it = customers.iterator();
while(it.hasNext()) {
if(it.next().getId() == id2) {
it.remove();
}
}
That's because you already removed one value, but the initial value in the condition (customer.size()) remains the same. So, the ACTUAL size of the list is 1, even though in the beginning was 2 or more.
What I would suggest is that instead of the for loop you use the iterator:
Iterator it = customers.iterator();
while (iterator.hasNext()) {
Customer customer= (Customer) it.next();
//do stuff with the customer
//remove the customer
it.remove();
}
there's a problem in your output.
After deleting the element with index i, you remember i.
int i1 = JOptionPane.showConfirmDialog(null,"the customer "
+ customers.get(remember).getName() + " has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
This piece of code, therefore, tries to access a deleted element from the list to get the name.
I would say you rewrite your method with the suggestions given by all previous answers. Something like this:
public void deleteCustomer(){
String id = null;
int remember = 0; //Remembers the deleted index
id = JOptionPane.showInputDialog(null,"input the id of whome you want to delete",
"input id", JOptionPane.PLAIN_MESSAGE);
int id2 = Integer.parseInt(id); //new int id.
Iterator<Customer> itr = customers.iterator();
while(itr.hasNext()){
Customer thisCustomer = itr.next();
if(id2 == thisCustomer.getID()){
customers.remove(thisCustomer);
break;
}
remember++;
}
if(remember < customers.size()){
JOptionPane.showConfirmDialog(null,"the customer has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
}
else{
JOptionPane.showConfirmDialog(null,"the customer could not be found," +
" please check your id",
"input people", JOptionPane.PLAIN_MESSAGE);
}
}
This is the method called when the player has to be removed from the game. Both these methods are in different classes.
GameboardGUI class
Vector<Player> players = new Vector<Player>();
public void removePlayerFromGame(Player playerToRemove)
{
//go through the playerToRemove's properties and reset all their variables
for(int i = 0; i < playerToRemove.getPropertiesOwned().size(); i++)
{
//code to reset the player's properties to an unowned/unmodified state
}
//same with transports
for(int i = 0; i < playerToRemove.getTransportsOwned().size(); i++)
{
//code to reset the player's transports to an unowned/unmodified state
}
//just updating the vector based on the playerToRemove's position
if(players.get(0) == playerToRemove)
{
players.remove(playerToRemove);
updatePlayerInformation();
}
else
{
players.remove(playerToRemove);
updatePlayerVector(players);
updatePlayerInformation();
}
}
This is how the method is called:
If the current player (fromMe) lands on a property and cant afford to pay the rent (i.e. their balance reaches 0 as a result of takefrombalance(1200);, currently hardcoded to 1200 to make testing easier) they are removed in the if statement if(fromMe.isBankrupt())
Property Class
GameboardGUI gui = new GameboardGUI();
public void payRent(Player fromMe, Player toYou, int rent)
{
//remove rent from the current player
fromMe.takeFromBalance(1200);
//add it to the owner
toYou.addToBalance(rent);
GameboardGUI.addGameFeedMessage(fromMe.getName() + " has paid " + rent + " in rent to " + toYou.getName());
GameboardGUI.addGameFeedMessage(toYou.getName() + "'s balance is now " + toYou.getBalance());
if(fromMe.isBankrupt())
{
//THIS IS THE CALL THAT THROWS THE NullPointerException
gui.removePlayerFromGame(fromMe);
}
else
{
GameboardGUI.addGameFeedMessage(fromMe.getName() + "'s balance is now " + fromMe.getBalance());
}
}
Here is the stack trace when the line is reached:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at PropertyTile.payRent(PropertyTile.java:254)
at PropertyTile.landedOnProperty(PropertyTile.java:239)
at GameboardGUI.playerHasLanded(GameboardGUI.java:1905)
at Player.setPosition(Player.java:82)
at Player.movePlayer(Player.java:101)
at GameboardGUI$11.actionPerformed(GameboardGUI.java:1536)
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$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)
It's really hard to help you without a stacktrace and the line numbers for your code, but we're trying.
If that's really the line (and not actually within removePlayerFromGame), the member gui hasn't been initialized.
Of course, if it's not that line, it could simply be that playerToRemove is null, and the NullPointerException is actually happening a couple of lines above.
Or, another possibility is that it's happening within removePlayerFromGame, in which case the most likely case is that playerToRemove hasn't been properly set up - that its getPropertiesOwned() or getTransportsOwned() methods are returning null.
I would add the following two lines, as a first step to see what happens:
if(fromMe==null)
System.out.println("from me is null");
if(gui == null)
System.out.println("gui is null");
gui.removePlayerFromGame(fromMe);
One of the two object references is null causing the exception.
Otherwise, the method removePlayerFromGame is doing something, but I don't think that would be the case because the stacktrace would include additional methods.
You say in the code that the Exception is thrown when you reach the line
gui.removePlayerFromGame(fromMe);
However, the top of stacktrace you are showing is Player.movePlayer(), with its bottom at PropertyTile.payRent().
Is this payRent() receiving any parameter? Can you post it source?