Michael Frans
Michael Frans

Reputation: 623

How to delete selected row in titanium tableview?

i make simple application on titanium using table view. I have some custom row with checkbox on the left side. Here's my code :

    var pickingData = [];

    for (var i = 0; i<25; i++){
        var row = Ti.UI.createTableViewRow({
            className:'forumEvent', // used to improve table performance
            backgroundSelectedColor:'cyan',
            layout:'vertical'
        });

        if (Titanium.Platform.osname === 'android'){
            var checkbox = Ti.UI.createSwitch({
                style:Ti.UI.Android.SWITCH_STYLE_CHECKBOX,
                value:false,
                left:10
            });
            row.add(checkbox);
        }

        var rndMatNo = (randomInt(50000)+10000) //randomInt is my random number function
        var lblMatNo = Ti.UI.createLabel({
            realValue:rndMatNo,
            text:'Mat No : ' + rndMatNo,
            font:{fontFamily:'Arial', fontSize:DefaultFontSize, fontWeight:'bold'},
            left:10,
            color:'#222'
        });
        row.add(lblMatNo);

        pickingData.push(row);
    }

    var tempPickingTable =  Titanium.UI.createTableView({
        data:pickingData,
        editable: Titanium.Platform.osname === 'iphone' ? true : false,
        name:'Picking table'
    });

    tempPickingTable.addEventListener('longclick',function(e){
        for (var i=0, length=tempPickingTable.data[0].rows.length;i<length;i++){
            if (tempPickingTable.data[0].rows[i].children[0].value === true){
                tempPickingTable.deleteRow(i); //Still error when i'm using delete row because index out of bound
            }

        }
    });

all i want is delete the row based on checkbox when it checked. i've tried looping for every row and check the checkbox and then delete the row, but it still give me error index out of bound.

has anyone know how to do that? thanks in advance..

Upvotes: 1

Views: 3722

Answers (2)

Dawson Toth
Dawson Toth

Reputation: 5680

You're iterating forward through the array, and deleting the rows, which modifies the array, so it makes sense that you'd go out of bounds. Have you tried iterating backwards?

tempPickingTable.addEventListener('longclick',function(e){
    for (var i=tempPickingTable.data[0].rows.length;i>=0;i--){
        if (tempPickingTable.data[0].rows[i].children[0].value === true){
            tempPickingTable.deleteRow(i);
        }
    }
});

Upvotes: 1

Sapan Diwakar
Sapan Diwakar

Reputation: 10956

There are some bugs in deleting rows from TableView in Android. You can try to create a new data array with all the rows except the ones that have been checked and then set the data for the tableview again.

Upvotes: 3

Related Questions