Step 7

Why handling life-cycle events is important

If you are used to always having control in your applications, you might not understand why all this life-cycle work is necessary. The reason is that in Android, you are not in control of your Activity, the operating system is!

As we have already seen, the Android model is based around activities calling each other. When one Activity calls another, the current Activity is paused at the very least, and may be killed altogether if the system starts to run low on resources. If this happens, your Activity will have to store enough state to come back up later, preferably in the same state it was in when it was killed.

Android has a well-defined life cycle. Lifecycle events can happen even if you are not handing off control to another Activity explicitly. For example, perhaps a call comes in to the handset. If this happens, and your Activity is running, it will be swapped out while the call Activity takes over.

Still in the NoteEdit class, we now override the methods onSaveInstanceState() , onPause() and onResume() . These are our life-cycle methods (along with onCreate() which we already have).

onSaveInstanceState() is called by Android if the Activity is being stopped and may be killed before it is resumed! This means it should store any state necessary to re-initialize to the same condition when the Activity is restarted. It is the counterpart to the onCreate() method, and in fact thesavedInstanceState Bundle passed in to onCreate() is the same Bundle that you construct as outState in the onSaveInstanceState() method.

onPause() and onResume() are also complimentary methods. onPause() is always called when the Activity ends, even if we instigated that (with afinish() call for example). We will use this to save the current note back to the database. Good practice is to release any resources that can be released during an onPause() as well, to take up less resources when in the passive state. onResume() will call our populateFields() method to read the note out of the database again and populate the fields.

So, add some space after the populateFields() method and add the following life-cycle methods:

a. onSaveInstanceState() : @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState);

outState.putLong(NotesDbAdapter.KEY_ROWID, mRowId);

@Override protected void onPause() { super.onPause(); saveState();

@Override protected void onResume() { super.onResume(); populateFields();

0 0

Post a comment