2

I want to avoid time consuming data loading during Fragment rotation.

public class WatchlistFragment extends SherlockListFragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (savedInstanceState == null) {
            data = getTimeConsumingData();          
        } else {
            Log.i(TAG, "savedInstanceState is not null!");
            // Avoid performing time consuming data operation during rotation changes.
            // But I never have chance to reach here !?!?
            data = savedInstanceState.getStringArray("data");
        }
        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data));
    }

    public String[] getTimeConsumingData() {
        Log.i(TAG, "WatchlistFragment getTimeConsumingData");
        return new String[] { "A", "B", "C"};
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.i(TAG, "WatchlistFragment onSaveInstanceState");
        super.onSaveInstanceState(outState);
        outState.putStringArray("data", data);
    }

    private String[] data = null;
    private static final String TAG = WatchlistFragment.class.getSimpleName();
}

Strangely, savedInstanceState in onActivityCreated is always null even I perform several rotation.

Note, I prefer not to use setRetainInstance(true) as described Android Fragments Retaining Data The author is using onSaveInstanceState. Just that I'm not sure why mine doesn't work.

Community
  • 1
  • 1
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

3 Answers3

1

Another approach is to use the new, super clever, Loader pattern, it's easy to implement and let the system handle all this for you:

http://developer.android.com/guide/components/loaders.html

Budius
  • 39,391
  • 16
  • 102
  • 144
0

just use setRetainInstance(true) in your fragment and check for savedInstanceState==null and dont override onSaveInstanceState

UPDATE

 private ArrayAdapter<String> adapter = null;
 public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setReatainInstance(true);
    if(adapter==null){
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,getTimeConsumingData());
    }
    setListAdapter(adapter);
}
Kapil Vats
  • 5,485
  • 1
  • 27
  • 30
  • Can you have complete code example? As I try to have `setRetainInstance` set to true, but Fragment still created each time there is rotation. – Cheok Yan Cheng Feb 25 '13 at 11:02
  • Strangely. I have `setReatainInstance(true);` in `onActivityCreated`. Not working. Moving it to `onCreate` is not working too. – Cheok Yan Cheng Feb 25 '13 at 11:21
0

If you are using loaders, Use loadermanager.destory(loader_id) after loading the data.It will wont load again for config changes.

Surya
  • 21
  • 1
  • 3