简体   繁体   中英

How to not delete variables in an activity in Android studio with going in a different activity?

I want to program an app but have big issues mentioned in the top. I have some variables in my main activity which, when I switch in a different activity and back again, are resetted. But I want that they keep there until I close the app. I cannot use SharedPreferences I think, because there, the value of the variables will be safed also when I close the app, which I doesn't want to. Please help...

What's most likely happening is your Activity is being killed and restarted. When this happens, you can implement onSaveInstanceState and onRestoreInstanceState to save and restore important information.

There is a limit to how much you can do via that though (about 1 MB). It works great for simple data structures, but you're not going to save bitmaps or big network responses that way. For that, you need to think about the right way to store things and what data belongs to the activity and should be scoped there vs the application and should be saved elsewhere and only accessed by the activity.

This answer https://stackoverflow.com/a/15083749/12408270 is probably what you want.

You can also use Intent.putExtra to pass data between activities.

Kotlin Companion objects might help you as well.

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