开发者

Android storage: OnSavedInstanceState not working?

I've read around SO and can't seem to find any answers regarding my problem. I've got an ArrayList of custom objects which implements Parcelable called listOfBuddies. I'm attempting to save it's state u开发者_如何学Csing the following code...

@Override
public void onSaveInstanceState(Bundle buddies){
    buddies.putParcelable("buddies", listOfBuddies);
    super.onSaveInstanceState(buddies);
}
@Override
public void onRestoreInstanceState(Bundle buddies) {
  listOfBuddies = buddies.getParcelable("buddies");
  super.onRestoreInstanceState(buddies);
}
public void onStart(Bundle buddies) {
    super.onStart();
    listOfBuddies = buddies.getParcelable("buddies");
    }

@Override
public void onCreate(Bundle buddies) {
    super.onCreate(buddies);
    setContentView(R.layout.buddylist);
    if(buddies != null){
        listOfBuddies = buddies.getParcelable("buddies");
    }
}

However, buddies always returns as null in OnCreate after restarting the Acitivty. Perhaps I'm going about this wrong... but basically I'd like to store the ArrayList of Objects for as long as my application is running.


I'm not sure if this will work, but I do have a suggestion. Instead of making the ArrayList itself implement Parcelable, try setting your custom object to implement Parcelable instead. Then use putParcelableArrayList and getParcelableArrayList to retrieve the list.


onSaveInstanceState is only called on a soft kill such as phone orientation change. On a hard kill you will need to persist activity state, perhaps by writing to prefs. If you choose this method of persisting state, then it goes without saying that you will need to read in prefs if the bundle is null. So the logic goes like this:

Set a flag isSaveInstanceState to false in onResume Set the flag to true in onSavedInstanceState In onStop if !isSavedInstanceState write to prefs

In onCreate:

If bundle != null retrieve state from the bundle else retrieve state from prefs

Document-like data is a different animal and may be persisted by a database write in onPause.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜