在片段旋转期间避免耗时的数据加载

时间:2013-02-25 10:54:29

标签: android

我想避免在Fragment轮换期间花费大量时间来加载数据。

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();
}

奇怪的是,即使我执行了多次轮换,savedInstanceState中的onActivityCreated始终为空。

注意,我不想按照Android Fragments Retaining Data使用setRetainInstance(true)使用onSaveInstanceState。只是我不确定为什么我的工作不起作用。

3 个答案:

答案 0 :(得分:1)

另一种方法是使用新的,超级聪明的Loader模式,它易于实现,让系统为您处理所有这些:

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

答案 1 :(得分:0)

只需在您的片段中使用setRetainInstance(true)并检查savedInstanceState==null并且不要覆盖onSaveInstanceState

<强>更新

 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);
}

答案 2 :(得分:0)

如果您正在使用加载器,请在加载数据后使用loadermanager.destory(loader_id)。它将不会再次加载配置更改。