ConcurrenModificationException with 2 dependent Combos (ZK Framework) - java

I have a zul wich has two dependent combos. When an item of the first combo (cb_empresa_detalle) is checked then the second combo (cb_agente_detalle) loads its items.
In my controller I have this code:
#EventHandler("cb_empresa_detalle.onSelect")
public void loadAgentes(Event evt) throws WrongValueException,
InterruptedException {
if (cb_empresa_detalle.getSelectedItem() != null) {
idEmpresa = (String) cb_empresa_detalle.getSelectedItem()
.getValue();
// cb_agente_detalle.getChildren().clear();
cb_agente_detalle.getItems().clear();
(...)
This code throws a ConcurrenModificationException in lines (I tried the following two options), when I check in diferent items in first combo:
cb_agente_detalle.getChildren().clear(); // is now comented
cb_agente_detalle.getItems().clear();
Also, I tried this:
while (cb_agente_detalle.getItemCount() > 0) {
cb_agente_detalle.removeChild(cb_agente_detalle.getFirstChild());
}
Any idea?

A ConcurrentModificationException is thrown when you try to delete items from a collection when you're iterating over it using an iterator.
Just make sure it is not the case.

Related

Hiding Multiple Elements in JTable via ButtonClick

I am currently working on a tool which edits data dynamically in a JTable. I want to hide the targeted row whenever a button is clicked. Right now I am using RowFilter. Whenever the button isClicked, a new filter is created:
RowFilter<MyTableModel, Object> rowFilter = null;
try {
rowFilter = RowFilter.notFilter(RowFilter.regexFilter(((String)dataTable.getValueAt(dataTable.getSelectedRow(), 0)),0));
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rowFilter);
This only works for one element each time the button is clicked. I want to stay them hidden, so you can continously hide elemtens in the table. It is important to mention that I do not want to delete the rows, just hide them.
I hope someone has an easy answer for this, looking for quite a while now.
This method sorter.setRowFilter(rowFilter); is replacing the filter every time you "add" a new filter. So, it's "forgetting" the old rules. What you have to do is edit the existing filter to include the new rules for filtering.
Check out the documentation for more details.
In any case, I extracted a part of the documentation which you should try to implement.
From RowFilter Javadoc:
Subclasses must override the include method to indicate whether the
entry should be shown in the view. The Entry argument can be used to
obtain the values in each of the columns in that entry. The following
example shows an include method that allows only entries containing
one or more values starting with the string "a":
RowFilter<Object,Object> startsWithAFilter = new RowFilter<Object,Object>() {
public boolean include(Entry<? extends Object, ? extends Object> entry) {
for (int i = entry.getValueCount() - 1; i >= 0; i--) {
if (entry.getStringValue(i).startsWith("a")) {
// The value starts with "a", include it
return true;
}
}
// None of the columns start with "a"; return false so that this
// entry is not shown
return false;
}
};
This means that the include() method is going to return true or false depending if an item should be shown.
Therefore, you should only set the RowFilter once, and reimplment the include() method to match all the rules you currently have set upon your view.

ConcurrentModificationException when updating a ListView that extends an ArrayAdapter

I have a ListView that has an adapter for each cell. This adapter extends ArrayAdapter (my object class).
The app also has 2 tabs so far. Tab 1 has the list, Tab 2 has a map.
Each cell in the adapter has a check box, which by default is unchecked.
The issue I have is that when I switch tabs the checked boxes return to be unchecked, and if I iterate an array of checked boxes, I get a ConcurrentModificationException when I try to mark a box as checked.
Here's my code of what I'm doing:
value_checkBox.setTag(route.getRouteShortName());
value_checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked == true)
{
RouteListLV.arrayOfRoutesEnabled.add(route);
}
else
{
RouteListLV.arrayOfRoutesEnabled.remove(route);
}
}
});
This part (the sample code above) works, and here's where I am adding the checked routes into a static array that can be used by multiple views.
for (Route routeFromArray : RouteListLV.arrayOfRoutesEnabled)
{
if (routeFromArray.getRouteShortName().equals(route.getRouteShortName() ) )
{
System.out.println("Match!");
value_checkBox.setChecked(true); <--- causes the ConcurrentModificationException
}
}
This loop (the for loop above) doesn't work and the exception happens when I set the checkBox to be checked.
I have tried an iterator as well, but I get the same result:
Iterator<Route> iterator = RouteListLV.arrayOfRoutesEnabled.iterator();
while (iterator.hasNext())
{
Route routeFromArray = iterator.next();
if (routeFromArray.getRouteShortName().equals(route.getRouteShortName() ) )
{
System.out.println("Match!");
value_checkBox.setChecked(true); <--- causes the ConcurrentModificationException
}
}
Any suggestions on this issue?
Just to be clear, I have 2 arrayLists. One is the one with the entire list of "routes" which is being passed to the ArrayAdapter to form the list, and I have a second arrayList for just the selected routes.
You're iterating through an ArrayList (RouteListLV.arrayOfRoutesEnabled) and modifying it as you go along. That causes a ConcurrentModificationException, so don't do it. Find a way to first find the element or elements you're going to modify and then modify the list (and never use the iterator after that). Or build a "shadow" copy of the list that has everything you want it to have at the end, then call removeAll() and then addAll(newList) on the original list, which is just that same idea in a slightly different form.

A List became empty without modifying it in java

Currently, I'm getting stuck with what it seems to be an unexpected error.
I'm programming with the java language, using eclipse as IDE.
The List in question is declared as follows :
private final List<Integer> resList;
Using the "Watchpoint" feature of eclipse while debugging the program, I've seen the following process :
After returning the resList List two times, and before returning it for the third time, the List became suddenly empty.
If anyone have a suggestion to give me in order to fix that problem, I would be very pleased ?
Concerning the code, I posted all the methods that access the resList list and are invoked in the program :
Here is the first One :
public CloudInformationService(String name) throws Exception {
super(name);
resList = new LinkedList<Integer>();
arList = new LinkedList<Integer>();
gisList = new LinkedList<Integer>();
}
And the second one :
public void processEvent(SimEvent ev) {
int id = -1; // requester id
switch (ev.getTag()) {
...
// A resource is requesting to register.
case CloudSimTags.REGISTER_RESOURCE:
resList.add((Integer) ev.getData());
break;
...
}
}
And finally, The third one :
private static CloudInformationService cis;
public static List<Integer> getCloudResourceList() {
if (cis == null) {
return null;
}
return cis.getList();// The implementation of this method is listed below
}
public List<Integer> getList() {
return resList;
}
Thank you in advance.
Step 1: use ctrl+alt+H to look up references to resList and look for methods calling remove, clear, removeAll. If there are too many methods using resList move on to Step 2.
Step 2: Set breakpoints in the CloudInformationServices constructor, when hit, set up breakpoints in LinkedList/AbstractList (in the JDK) in all remove, clear, removeAll methods. In the breakpoints view, right click on resList and choose instance breakpoints. Pick all your remove, clear, removeAll breakpoints and continue execution. Now you'll get a breakpoint hit and can observe from where the list is being emptied.
Without any more code there isn't much help you can get I'm afraid.

Error removing element from JList with DefaultListModel

I have a standard JList that will be changed while the program is running. In order to make life easier I have created a DefaultListModel and assigned it to the JList:
JList CharList = new JList();
DefaultListModel CharListModel = new DefaultListModel();
CharList.setModel(CharListModel);
I am able to load a file into the list, and later I can add items to the list like this:
File ChFile = new File (CharListFile);
FileReader freeder = new FileReader (ChFile);
BufferedReader breeder = new BufferedReader(freeder);
String line;
while((line=breeder.readLine())!=null)
{
int pos = CharList.getModel().getSize();
CharListModel.add(pos, line);
}
...
...
//and to add items..
int pos = CharList.getModel().getSize();
CharListModel.add(pos, NewCharName);
However, I need to be able to remove items from the list, and this is giving me some considerable trouble!
I have tried the most obvious way (Yes an item is selected, and I have already retrieved both the index and the string at that index):
CharListModel.removeElement(CharList.getSelectedValue());
However, this gives me a 'java.lang.ArrayIndexOutOfBoundsException: -1' error.
I have tried all of the permutations that you can see in the code below (Some are commented out but you get the idea):
DefaultListModel model = (DefaultListModel) CharList.getModel();//CharListModel;
int selectedIndex = CharList.getSelectedIndex();
if (selectedIndex != -1) {
//model.remove(selectedIndex);
//model.removeElement(CharList.getSelectedValue());
//model.removeElementAt(selectedIndex);
}
as well as a few other permutations as well:
CharListModel.removeElementAt(CharList.getSelectedIndex());
//or
CharListModel.remove(CharList.getSelectedIndex());
//or
CharList.remove(SelItemIndex);
In each case I get the same 'ArrayIndexOutOfBoundsException' error, even though the selected index is previously found with no trouble. And yes, I know I just said 'previously' so something could have changed things, but here is the code that runs directly before I try to remove the element:
int SelItemIndex = CharList.getSelectedIndex();
if(SelItemIndex == -1)
{
JOptionPane.showMessageDialog(null, "You have to select something!");
return;
}
String SelItem = CharList.getModel().getElementAt(SelItemIndex).toString();
//Create warning
final JComponent[] inputs = new JComponent[]
{
new JLabel("<html>Bla Bla " + SelItem + " Are you sure?</html>")
};
int n = JOptionPane.showConfirmDialog( null, inputs,"Deletion Confirmation Warning", JOptionPane.YES_NO_OPTION);
if( n == 1)
{
//Do not delete
return;
}
That is all there is before trying to remove the selected element.
For the life of me I don't know why this is not working! Am I missing something really silly here?
A confusing update
In the ActionPerformed event of a JButton I have used this code - The comments in the code explain why this is so confusing!:
DefaultListModel CharListModel = (DefaultListModel)CharList.getModel();
if( CharListModel.contains(CharList.getSelectedValue()) == true)
{
//Selected item is found
int selItemIndex = CharListModel.indexOf(CharList.getSelectedValue());
if(selItemIndex != -1)
{
//Selected item index is NOT -1 and is correct
CharListModel.remove(selItemIndex);
//Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
}
else
{
//NEVER reached
JOptionPane.showMessageDialog(null, "OUCH!");
}
}
As you can see, the index of the selected item is correct right up to the point of removing it, whereupon I once again get the out of bounds exception. I also tried this in the same place but with the same results:
CharListModel.removeElement(CharList.getSelectedValue());
Even more confusion
In an attempt to work out what is going on I have created a new DefaultListModel, enumerated the old one, and put each name into the new model, except the one that I want to remove (Remember I can get the index, the object and the text, I just cant delete it).
This has worked and I now have a DefaultListModel with the correct items in it, however, the moment that I try to CharList.setModel(NewModel); I once again get the out of bounds exception.
This has got me pulling out hair! Can anyone offer any ideas to try?
A Resolution of sorts
Not really a resolution at all, but to work around this maddening problem I am using the method laid out above, where I create a copy of the list model, minus the item that I want to delete and then simply catch the exception when using setModel, since the updated list model is added to the list just fine, and subsequent actions such as adding items etc. work okay, right up until I try to delete an item again anyway!
Thanks if you tried to help - and if you have any ideas about how to hunt down this problem, by all means post away!
regards
Max
For reference, I added the code below to this example. If it's not helpful, it may be a useful sscce for updating your question.
panel.add(new JButton(new AbstractAction("Remove") {
#Override
public void actionPerformed(ActionEvent e) {
int index = list.getSelectedIndex();
if (index != -1) {
model.remove(index);
}
}
}));
I had a similar problem. It turned out the error stemmed not from removing the element, but rather displaying the list. When implementing the
public void valueChanged(ListSelectionEvent e)
method, which updates the list on the screen, make sure to check if the model is null before you set the values. This is what caused the exceptions in my case.
Creating a list, removing from there, and then updating the model with the list is also a usable workaround.
I have faced the same issue. It seems when the item is removed from the model, it gets removed from the array as well. Hence is messes up the array index.
As a work around, I moved the array contents into a List and remove the List contents from the model. Now it works fine for me.
I have the same problem, i fix this doing that:
Button Action
int index = mylist.getSelectedIndex();
MyObject = (MyObject) mylist.getSelectedValue();
int Size = mylistmodel.getSize();
if (index >= 0 && MyObject != null && Size > 0) {
modeloLista.removeElementAt(indice);
}
And.
listValueChanged
if (list.getSelectedValue() != null) {
your code..
}

Java Programming Error: java.util.ConcurrentModificationException

I'm writing a program as part of tutorial for a beginner Java student. I have the following method and whenever I run it, it gives me the following exception:
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Warehouse.receive(Warehouse.java:48)
at MainClass.main(MainClass.java:13)
Here's the method itself, within the class Warehouse:
public void receive(MusicMedia product, int quantity) {
if ( myCatalog.size() != 0) { // Checks if the catalog is empty
// if the catalog is NOT empty, it will run through looking to find
// similar products and add the new product if there are none
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}
} else { // if the catalog is empty, just add the product
myCatalog.add(product);
}
}
The problem seems to be with the if else statement. If I don't include the if else, then the program will run, although it won't work properly because the loop won't iterate through an empty ArrayList.
I've tried adding a product just to keep it from being empty in other parts of the code, but it still gives me the same error. Any ideas?
You can't be iterating through the same list you're going to add things to. Keep a separate list of the things you're going to add, then add them all at the end.
You must not modify mCatalog while you're iterating over it. You're adding an element to it in this loop:
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}
See ConcurrentModificationException and modCount in AbstractList.

Categories