简体   繁体   中英

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 using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM