Thursday, May 5, 2011

How to cache views with Android and avoid calling onCreate everytime.

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 :)

From stackoverflow
  • 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);
    
  • If it gets called it means your process finished executing or was killed by the system.

    onCreate will get called each time your activity starts. That's just the way the Activity lifecycle works and there's not much you can do there.

    If you wish that your process remain in memory then you should consider implementing it as a Service.

  • 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.

  • 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.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.