How to save state of Fragment having listview
android, android-listview, fragment, java
Solution
As explained here you can use onSaveInstanceState() to save data in the Bundle and retrieve that data in the onRestoreInstanceState() method.
Often setRetainState(true) is mentioned as way to keep the ui state in fragment, but it does not work for you because you are using the backstack.
So a good way for you could be to save the scrollposition in onSaveInstanceState() and restore it in onRestoreInstanceState() like this:
public class MyListFragment extends ListFragment {
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
int index = this.getListView().getFirstVisiblePosition();
View v = this.getListView().getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
outState.putInt("index", index);
outState.putInt("top", top);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
[...]
if (savedInstanceState != null) {
// Restore last state for checked position.
index = savedInstanceState.getInt("index", -1);
top = savedInstanceState.getInt("top", 0);
}
if(index!=-1){
this.getListView().setSelectionFromTop(index, top);
}
}
Further more you can find a more detailed similiar example here.
Problem
Here is a situation. I want to navigate from Fragment A-> B-> C. In B Fragment there is listview. On item click I open the detail view C Fragment. Ofcourse I used replace method and added addtoBackStack(null) while transactiong from B to C so that on Back press it returned to B. All goes well. But when I return to B from C, the view is being refreshed and hence the webservice is being called again. I don't want to do this. I want to retain the B Fragment state with listview. I got some post of Retain Instance, but it didn't help that much. Any help is much appreciated. Thanks.