Search code examples
androidbuttononclicklisteneractivity-lifecycle

Android Button Listener lifecycle


I want to make sure my app works as efficiently as possible and am looking into the activity lifecycle. Particularly, I create the Button setOnClickListeners in the activity onCreate.

From my understanding, android can clear up resources after onPause or onStop. Does that mean I have to check whether the listeners still exist and re-create them if needed in onResume? When user clicks back, home, gets a call, etc.


Solution

  • Right, Android can clean up resources, but not runtime-important objects in memory :-) The Listeners you set will stay there as long as the Views themselves. However, things you reference inside the Listeners may not be there when they are invoked, so make sure to check whether objects you access are not null :-)

    If you need more insight into that, do some reading on how the Java gc mechanism works :-) The Views inside Activity are bound to its gc tree, so they are safe as long as the Activity is there. And when it is recreated, the onCreate will be called again :-)

    Here you have a quick example:

    /** This is hand code, it won't compile most probably ^^ **/
    public class myActivity extends Activity {
        private DataBase db;
        private Button button;
    
        public void onCreate(){
            db = /* init db somehow */
            button = (Button) findViewById(R.id.button);
            button.setOnclickListener(new OnClickListener() {
                public void onClick(View view) {
                    db.doSomething();
                }
            });
        }
    
        public void closeDatabase() {
            db = null;
        }    
    }
    

    And now imagine that for some reason you called the closeDatabase() method. If the user clicks the button after that, the app will crash with a NullPointerException.

    This is of course a direct example (i.e. you are making the db object null in the code) but it may happen automatically inside the system and (rarely) because gc may free something big, like an image.