简体   繁体   中英

Android: How to restore List data when pressing the “back” button?

My question is about restoring complex activity related data when coming back to the activity using the "back" button". Activity A has a ListView which is connected to ArrayAdapter serving as its data source - this happens in onCreate().

  1. By default, if I move to activity B and press "back" to get back to activity A, does my list stay intact with all the data or do I just get visual "copy" of the screen but the data is lost?
  2. What can I do when more than activities are involved? Let's say activity A starts activity B which starts activity C and then I press "back" twice to get to A. How do I ensure the integrity of the A's data when it gets back to the foreground? PrefsManager does not seem to handle complex object very intuitively.

Thanks, Rob

Activity A has a ListView which is connected to ArrayAdapter serving as its data source

Note that an ArrayAdapter is not a persistent store.

By default, if I move to activity B and press "back" to get back to activity A, does my list stay intact with all the data or do I just get visual "copy" of the screen but the data is lost?

That depends.

Typically, Activity A has not gone anywhere. However, if the user leaves the app for an extended period, Android may destroy Activity A, leaving a placeholder in the activity stack, to free up memory. If, later, the user presses BACK, Android will re-create Activity A. You need to hang onto your data in this case, either by using a persistent store (file, database, etc.) or by using onSaveInstanceState() and onRestoreInstanceState() .

You can find more in the Activity Lifecycle section of the Activity class description.

除非您在启动活动B时主动finish()活动A,否则无论您堆叠多少活动,活动B的数据和状态都将在您返回时显示。

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