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

Time:12-17

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related