DEV Community

remix
remix

Posted on

Quick Tip. Don't use Fragment.setRetainInstance(true)!

I'm developing android app for few months.

TL;DR
just don't. don't use it. don't create zombie. let them die.

Long story.
I was making nice feed in android app, using fragments. And I thought if I rotate my phone my feed is recreating. That's bad. So I used setRetainInstance(true). And it solved this trouble for short period of time. But then it brings million others. Your fragment that survived rotation is attached to old activity which is dying slowly. (yeah, android is such a retarded in this way but nvm). And so when you try to do smth with it after some period it will die.
Also you can't run any of the method of this fragment from your activity. For example survivedFragment.doSomth() - when you run this android will tell fragment that his context is dead and you can't reattach new activity to it. But even without running command, the dying activity will eventually die and your fragment will too.

So I come to conclusion that you shouldn't use setRetainInstance(true) on a fragment that has at least 1 view object.

Thanks, and shoutout to google: I hate android lifecycle. I think android lifecycle wasted some trillion of human life hours.

Top comments (0)