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

Asked

Viewed 133 times

1

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

I need to fill 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 pick the last item from the list even when it is not selected.

But if I remove the section that’s 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 sql.

So my question is: How I remove the comma only after the last selected item?

I hope you can understand my doubt.

  • In short, you always want to add the comma to the ufSelected within the for, except when it is the last item in the list?

  • @Statelessdev, that’s exactly what I understood too.

  • Exact, except however after the last selected item, which is not necessarily the last one on the list. Ex: In a list with the items: (Acre, Amazonas, Amapá, Bahia, Ceará), if the user selects only (Amazonas, Bahia) the result should be ufSelecionado = 'Amazonas','Bahia' ufSelecionado = 'Amazonas','Bahia','Ceará' even if the user does not choose the item Ceará. And if I take the line of code out of the loop is the result is: ufSelecionado = 'Amazonas','Bahia',

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(","));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.