Reputation: 3969
The only way that I see is to use a static variable
, but it's not okay as I want to keep the ability to start multiple Activites
.
In my case, I want to keep a reference of Dagger 2 Component
.
It will provide objects like Navigator
. I can't just store it into Bundle
.
For now, I can't use Retain MainFragment
instead of MainActivity
because of this bug.(I'm at 23 API level)
Is there any Retain Activity implementation?
Upvotes: 1
Views: 1018
Reputation: 1712
Huh, well you have two built in solutions in android to fix this problem:
1) If the object is serializeable or parcelable you can override onSaveInstanceState() and read the value out in onCreate. Here are the google developer docs for the specifics on that.
2) If your object is not serializable you can instead override onRetainNonConfigurationInstance() and return that object. You can then get the object back in onCreate. Look at this SO post for how to use this approach (don't persist your activity though! persist the object.). The drawback of this is that you can only persist one object at a time.
I have a more in depth write up of these two approaches and third, declarative approach that you can roll. It relies on onRetainNonConfigurationInstance and allows you to use annotations to declare what variables in your activity should be persisted. check it out here. That said, I wouldn't recommend using this unless you have more than one non-serializeable/parcelable object to persist.
Edit: clarified point that you shouldn't persist your whole activity using onRetainNonConfigurationInstance().
Upvotes: 1