How to know which is the last item selected from a listView?

1

Hello, I have a ListView using simple_list_item_multiple_choice , filled with ArrayString of all Brazilian states.

I need to fill in the following SQL command with all the states selected by the user through the ufSelected String:

SQL Cursor cursor = database.rawQuery("SELECT * FROM PALAVRAS WHERE _estado IN ("+ ufSelecionado + ")", null);

For this I am using the following code:

SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
String ufSelecionado = "";
int cntChoice = listView.getCount();

for ( int i = 0; i < (cntChoice-1); i++) {
    if (sparseBooleanArray.get(i)) {
        ufSelecionado += "'"+ listView.getItemAtPosition(i).toString() + "'" + ", ";
    }

}

ufSelecionado += "'"+ listView.getItemAtPosition(i).toString() + "'";

The problem is that using this method the variable ufSelecionado will always catch the last item in the list even when it is not selected.

But if I remove the snippet that is out of the loop:

ufSelecionado += "'"+ listView.getItemAtPosition(i).toString() + "'";

The result will always contain a comma (,) after the last selected item which generates error in the command SELECT of sql.

So, my question is: How do I remove the comma just after the last selected item?

I hope you can understand my question.

    
asked by anonymous 18.05.2018 / 20:40

1 answer

0

Whatever the value assigned to your variable ufSelecionado , 'Amazonas','Bahia','Ceará' or 'Amazonas','Bahia', the solution is simply:

ufSelecionado = ufSelecionado.substring(0, ufSelecionado.lastIndexOf(","));
    
18.05.2018 / 22:39