Mortalus
Mortalus

Reputation: 10712

how to get Checked Items from list view that was filtered from the adapter

I have a list view with a custom ArrayAdapter. I have created a custom chackable linear layout and so far every thing works great with this code:

public ArrayList<FBFriend> getSelectedFriends()
{
    ArrayList<FBFriend> checkedFriends = new ArrayList<FBFriend>();
    SparseBooleanArray checkedItems = m_FriendsListView.getCheckedItemPositions();
    int size = checkedItems != null ? checkedItems.size() : 0;
    for (int i = 0; i < size; i++)
    {
        if (checkedItems.valueAt(i) == true)
        {
            FBFriend selectedFriend = m_FriendsList.get(checkedItems.keyAt(i));
            checkedFriends.add(selectedFriend);
            Log.i(TAG, "Selected Friend:" + checkedItems.keyAt(i) + " - " + selectedFriend.toString());
        }
    }

    return checkedFriends;
}

when i filter my list of friends using this:

public void onInputFriendSearchTextChanged(CharSequence cs, int arg1, int arg2, int arg3)
{
    m_FBFriendsListAdapter.getFilter().filter(cs);
    m_FBFriendsListAdapter.notifyDataSetChanged();
}

the method above (getSelectedFriends) returns the wrong friends becuse it considers the selected positions and not the selected IDs.

I have defined in my adapter the following in hope that it will cause the getCheckedItemPositions method to use the IDs:

@Override
public long getItemId(int position)
{
    FBFriend friend = getItem(position);
    return Long.parseLong(friend.getID());
}

@Override
public boolean hasStableIds()
{
    return true;
}

but it did not help ...

any way to get the correct selected items when the list adapter is filtered ?

Upvotes: 0

Views: 696

Answers (1)

Mortalus
Mortalus

Reputation: 10712

Found the BUG !!!

the reason was in method extracting the selected item. I have used this:

FBFriend selectedFriend = m_FriendsList.get(checkedItems.keyAt(i));

but actually i cannot call get on the list becuse it will not keep track on filtered items. what sholud be done is:

FBFriend selectedFriend = m_FriendsListAdapter.getItem(checkedItems.keyAt(i));

so the ArrayAdapter actually keep track on the new position of each item according to the filter and will return the correct item.

Upvotes: 3

Related Questions