tags:

views:

1597

answers:

4

Hello everyone, I've got a question that is annoying me.

With Android, I've got an application that seems calling "onCreate" every time on a new instance of an activity, 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" everytime seems to be re-parsing the xml to create the views and re-attaching/re-creating the listners to the code and so on. So Is there a way to "cache" an activity to be recalled everytime, without seeing it if we click on "back" in the mobile devie? it's like having it really hidden (not accessible with the back button) and destroyed only if it's necessary.

Thanks everyone on advance :)

A: 

Maybe something like this will help you

Define a variable

private static View mView = null;

Than in onCreate

if (mView == null) {
    mView = LayoutInflater.from(this).inflate(R.layout.YOUR_LAYOUT, null);
}
setContentVIew(mView);
alexkipar
Thanks for your answer, but how to create listeners and attach them to the Activity just once, I've tried your solution, but everytime I call my activity, the emulator freeze.
+1  A: 
JRL
Thank you for the answer, but as I said, I've got no problem in calling "onCreate" everytime, but I want to have to inflate my view and attach listners to it in the activity just once. So by avoiding calling finish it seems possible but it gives me the side effect of getting all the views while clicking on the "back" button in the emulator.
+4  A: 

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.

Soonil
A: 

You can not prevent onCreate from being called at every Activity creation because that is the way things work.

Your problem here is more an architecture problem : you have a feature that you use very often but you dedicate a whole heavy activity to it.

If you are looking for speed and responsiveness, an answser can be the ViewFlipper. You define an unique Activity, and when you use your feature, you just change the view. You entire app is loaded at the very start, then it stays in memory until Dalvik needs some. You can find a pretty complex example in the code of the open source app astrid.

e-satis