androidlistviewandroid-listviewandroid-cursoradapter

Get ListView item position by uri / by the data it contains


I have a ListView which I populate using a custom CursorAdapter. Now I want to manually update just one specific item in the ListView. I have the content URI of that item. Is it possible to use just this info to get the position of the item in the listView? If I have the position I can do something like

View v = mListView.getChildAt(itemPosition - mListView.getFirstVisiblePosition());

to update the view. But how can I get itemPosition?

I know that I get the position in the onItemClickListener, but I need to update the view without it being clicked.

Any help guys?


Solution

  • ListView does not support updating a single position.

    You must update the adapter with the new data (even if you change a single position) and the, invoke mAdapter.notifyDataSetChanged()

    If you get the View by its position (via listView.getChildAt()) will work. However, if you scroll up and down the list, that view will display the old data again because the adapter is not aware of the change (and it is the adapter which update the view contect view getView()).

    When you invoke notifyDataSetChanged(), you are telling to the adapter that your data set has new info and the ListView/Adapter will re-draw the visible items (it won't re-draw whole list at once.. only the visible items).

    You may want to consider to change to RecyclerView in the future. The BaseAdapter used in a RecyclerView support actions such as add/remove/update a single position.