1. Download our Official Android App: Forums for Android!

Apps How to remember listview position and selection

Discussion in 'Android Development' started by kaliki, Mar 8, 2010.

  1. kaliki

    kaliki Newbie
    Thread Starter
    Rank:
    None
    Points:
    15
    Posts:
    11
    Joined:
    Jan 21, 2010

    Jan 21, 2010
    11
    0
    15
    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 Newbie
    Rank:
    None
    Points:
    16
    Posts:
    11
    Joined:
    Oct 23, 2009

    Oct 23, 2009
    11
    2
    16
    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 Newbie
    Thread Starter
    Rank:
    None
    Points:
    15
    Posts:
    11
    Joined:
    Jan 21, 2010

    Jan 21, 2010
    11
    0
    15
    Thanks that worked great
     
  4. navsoftdev87

    navsoftdev87 Lurker
    Rank:
    None
    Points:
    5
    Posts:
    4
    Joined:
    Jun 9, 2011

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

    alostpacket Over Macho Grande?
    Rank:
    None
    Points:
    513
    Posts:
    7,973
    Joined:
    Nov 29, 2009

    Nov 29, 2009
    7,973
    3,603
    513
    Android App Developer
    NY
    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...