Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setRetainInstance fragment with UI Android

Ok, I created a Fragment with some UI (couple textboxes and stuff) and I used setRetainInstance since Im running an AsyncTask to query a server (request can only be sent once) and I need the result of the AsyncTask. So my question is: Is it wrong to retain the whole fragment with the UI? I saw couple examples where people use an extra Fragment to use the setRetainInstance but.. is there anything wrong not using that extra one?? If there is an issue with using the setRetainInstance why is that? Couldn't find any info in the documentation regarding this.

like image 919
Raykud Avatar asked May 16 '12 22:05

Raykud


1 Answers

Even if you use setRetainInstance(true), your Fragment will still recreate its views when you rotate (you will get a call to onDestroyView and then onCreateView). As long as you don't keep references to views past onDestroyView, there will not be any leaks of the old Activity. The best approach would be to explicitly null the references in onDestroyView, but your code in onCreateView would generally overwrite those references anyway.

There are many examples online (including some official ones) where people use a separate fragment (without a view) to retain data. Assuming what I said above is correct, then this is unnecessary (for the sake of preventing leaks). In many cases, you may end up with cleaner code/architecture if you use a separate fragment whose responsibility is just to handle the data and not worry about the UI.

You can check to see if you are leaking Activity contexts after rotating by using Eclipse MAT.

like image 122
antonyt Avatar answered Oct 11 '22 18:10

antonyt