Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory issues with a large number of fragments in back stack

I have an activity where the user can progress from one fragment to another. The fragment starts, downloads some data and displays it (along with drawing some icons from resources, etc). The user can continue moving forward through fragments for as long as they like (until they get bored?).

The problem is, an OutOfMemoryError will eventually happen (after around 90 fragments on a 32mb vm heap). 90 does seem like quite a lot, but I have seen such memory error reports in the field, so probably this happens earlier on lower-end devices. I have made sure any views I create in onCreateView I nullify in onDestroyView. The only other objects my fragments hold (as far as I can tell) are the data it downloads at the start, usually only 10-50kb.

My first question is, is this normal? Can I expect to 'only' be able to have ~90 fragments in the back stack? Or do I have a memory leak somewhere that I can do something about?

If the user goes away from my app, and Android decides to kill the whole process to free memory, when the user returns the memory used is much less because the whole state has been restored from bundles. If the user then back-presss through the back stack, each fragment is then of course created/resumed from savedinstancestate.

So my second question is, is there a way to force this to occur? Ie, 'if there are >50 fragments in the back stack, start killing the ones at the bottom to savedInstanceState?'

like image 280
rockgecko Avatar asked Dec 19 '12 04:12

rockgecko


Video Answer


1 Answers

All back stack Fragment are kept in memory with hard references. So if you are keeping a ridiculous amount of Fragments in back stack then you will get out of memory.

Have a look here: When a Fragment is replaced and put in the back stack (or removed) does it stay in memory?

like image 169
M-WaJeEh Avatar answered Nov 15 '22 08:11

M-WaJeEh