Toan Tran Van
Toan Tran Van

Reputation: 759

Passed variable in onSaveInstanceState() is cleared in onDestroy

I asked this question: savedInstanceState.getParcelableArrayList() return empty list

But now, I found that this problem is related to my onDestroy() method.

I save my ArrayList called mVideos in onSaveInstanceState() and clear all it's items inside

onDestroy (I thought doing this will save memory when app is killed).

In onCreate() I restore saved mVideos, BUT It returned empty list

My Code:

   @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

    if (mVideos != null)
        mVideos.clear();

    mVideos = null;
}

@Override
protected void onSaveInstanceState(Bundle out) {
    // TODO Auto-generated method stub

    out.putParcelableArrayList(VIDEO_LIST, mVideos);
    super.onSaveInstanceState(out);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        ArrayList<Video> saved = savedInstanceState.getParcelableArrayList(VIDEO_LIST);
       Log.e(VIDEO_LIST, "Count: " + saved.size());
    }
}

--> saved.size() = 0. If I remove mVideos.clear() in onDestroy() it works correctly

I know that onSaveInstanceState() is called right after onPause(). BUT why in this case, why onDestroy

effects to saved variable?

Upvotes: 0

Views: 969

Answers (1)

romtsn
romtsn

Reputation: 11982

I think, that in onSaveInstanceState Android saves a pointer to the memory area, so when you calling mVideos.clear(), that memory area is clearing, and when you trying to restore it, it returns an empty list.

Upvotes: 1

Related Questions