How to remove a line from a table

Hi,

Here is an issue about the Table/IndexedContainer objects, hope some of you will help me ! :

I create a table with 3 columns : N° of line (1, 2, 3, …), Name, Phone number
what i do :
- I select the row N°2 of the table,
- i click on the “Remove Line” button, the line N°2 is removed,
- the first column becomes un-ordered (1, 3, 4, 5), so the “for” loop below updates this column : 1, 2, 3, … => OK

BUT, if i redo the same actions with the new line N°2 (which was the line N°3 before), i get a Null Pointer Exception because, from the Table point of view, the line N°2 doesn’t exist any more, so his field “Num” cannot be updated !!

contactRemovalButton = new Button("-", new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					Integer id = (Integer) table.getValue();
                                        // ic is an IndexedContainer, it is used by my table object
					Integer numberItem = (Integer) ic.getContainerProperty(id, "Num.").getValue();
					ic.removeItem(id);
					for(int i=numberItem+1;i<ic.size()+2;i++){
						ic.getContainerProperty(i, "Num.").setValue(i-1);
					}
				} 
			});

So, i am searching for a solution which allows me to remove the selected line of a table, AND updates the Num column by selecting all the remaining lines one by one for updating the Num field.
12679.jpg

I think you have to change your loop to:

for (Object itemId : ic.getItemIds()) {
    Item item = ic.getItem(itemId);
    int index = (Integer)item.getItemProperty("num").getValue();
    if (index > numberItem) {
        item.getItemProperty("num").setValue(index - 1);
    }
}

or use

table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX);

Maybe not 100% correct, but should point you in the right direction.

[size=2]
Many thanks Kim, it works fine ! :grin:

Here is the final code :

contactRemovalButton = new Button("-", new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					String [color=#0a780a]
numberItem
[/color]= (String) table.getContainerProperty(table.getValue(), "Num.").getValue();
					Integer [color=#471ecc]
id
[/color] = (Integer) table.getValue();
					ic.removeItem([color=#471ecc]
id
[/color]);
					
					for (Object itemId : ic.getItemIds()) {
					    Item [color=#a86c13]
item 
[/color]= ic.getItem(itemId);
					    String str_index = (String)[color=#a86c13]
item
[/color].getItemProperty("Num.").getValue();
					    int index = Integer.parseInt(str_index);
					    if (index > Integer.parseInt([color=#0a780a]
numberItem
[/color])) {
					        [color=#a86c13]
item
[/color].getItemProperty("Num.").setValue(index - 1);
					    }
					}
				} 
			});

I do not use
table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX);
because i do not know how to add a title to this column.
[/size]