How to cache views with Android and avoid calling onCreate everytime

EB- Iliass picture EB- Iliass · Apr 27, 2009 · Viewed 8.6k times · Source

I've got a question that is annoying me.

With Android, I've got an application that seems to be calling onCreate every time a new instance of an activity is created, because this activity is the son of an another and it finishes itself while it ends its role for one piece of data.

The calling of onCreate every time seems to be re-parsing the XML to create the views and re-attaching/re-creating the listeners to the code and so on. So Is there a way to cache an activity to be recalled every time, without seeing it if we click on the back button in the mobile device? It's like having it really hidden (not accessible with the back button) and destroyed only if it's necessary.

Thanks everyone in advance :)

Answer

sooniln picture sooniln · May 3, 2009

Android will handle most applicable View and activity caching and you shouldn't have to worry about it. I -strongly- warn against alexkipar's approach. This is quite naive and will only worsen performance as well as create memory leaks and flat out wrong behavior.

If you feel Activity's are being created too often, I would recommend making sure you are using and understanding the Activity lifecycle correctly. As with every system, Android balances between efficiency and reusability, and there are always tradeoffs to make.

A common misconception you mentioned involves parsing XML. XML for views is not stored as pure XML, but rather in a compiled form for efficiency. You do not have to worry about this, trust that the system is trying to make things as efficient as it can for you.