How to remember listview position and selection


Last Updated:

  1. kaliki

    kaliki Member This Topic's Starter

    Joined:
    Jan 21, 2010
    Messages:
    11
    Likes Received:
    0
    Hi there
    I have a problem with a listview i'm using. I load the data in the listview from a cursorAdapter and when i select an item an onItemClickListener launches the corresponging activity. Now when i press the back button i would like
    the listview to remember the previous position and selection but it just loads the list from the start, none of these is remembered.Can anyone help me with an example? Thank you
     

    Advertisement
  2. Zero

    Zero Member

    Joined:
    Oct 23, 2009
    Messages:
    11
    Likes Received:
    2
    You need to save the selection position before refreshing your adapter. I use this in onRestart():

    Code (Text):
    1.  
    2.         int selection = mListView.getSelectedItemPosition();
    3.         mAdapter.refresh(); //reload the data, refresh is my own method, you can
    4. //use notifyDataSetChanged()/Invalidated()
    5.         mListView.setSelection(selection);
    6.  
     
  3. kaliki

    kaliki Member This Topic's Starter

    Joined:
    Jan 21, 2010
    Messages:
    11
    Likes Received:
    0
    Thanks that worked great
     
  4. navsoftdev87

    navsoftdev87 New Member

    Joined:
    Jun 9, 2011
    Messages:
    4
    Likes Received:
    0
    Should i pass the selected item position to the next screen?
     
  5. alostpacket

    alostpacket Over Macho Grande? VIP Member

    Joined:
    Nov 29, 2009
    Messages:
    7,978
    Likes Received:
    3,603
    If you need it on the next screen :) Otherwise it's better to save in the instance state.


    You guys may want to look at Loader too if you are using cursor/simplecursor adapters

    It's new in Android 3.0 but they added it to the compatibility package so you can use it all the way back to 1.6

    hth
     

Share This Page

Loading...