Step 6

The above createNote() and onListItemClick() methods use an asynchronous Intent invocation. We need a handler for the callback, so here we fill in the body of theonActivityResult() .

onActivityResult() is the overridden method which will be called when an Activity returns with a result. (Remember, an Activity will only return a result if launched withstartActivityForResult.) The parameters provided to the callback are:

• requestCode — the original request code specified in the Intent invocation (either ACTIVITY_CREATE or ACTIVITY_EDIT for us).

• resultCode — the result (or error code) of the call, this should be zero if everything was OK, but may have a non-zero code indicating that something failed. There are standard result codes available, and you can also create your own constants to indicate specific problems.

• intent — this is an Intent created by the Activity returning results. It can be used to return data in the Intent "extras."

The combination of startActivityForResult() and onActivityResult() can be thought of as an asynchronous RPC (remote procedure call) and forms the recommended way for an Activity to invoke another and share services.

Here's the code that belongs in your onActivityResult() :

super.onActivityResult(requestCode, resultCode, intent); Bundle extras = intent.getExtras();

switch(requestCode) { case ACTIVITY CREATE:

String title = extras.getString(NotesDbAdapter.KEY_TITLE); String body = extras.getString(NotesDbAdapter.KEY_BODY); mDbHelper.createNote(title, body); fillData(); break; case ACTIVITY_EDIT:

Long mRowId = extras.getLong(NotesDbAdapter.KEY ROWID); if (mRowId != null) {

String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE); String editBody = extras.getString(NotesDbAdapter.KEY_BODY); mDbHelper.updateNote(mRowId, editTitle, editBody);

fillData(); break;

• We are handling both the ACTIVITY_CREATE and ACTIVITY_EDIT activity results in this method.

• In the case of a create, we pull the title and body from the extras (retrieved from the returned Intent) and use them to create a new note.

• In the case of an edit, we pull the mRowId as well, and use that to update the note in the database.

• fillData() at the end ensures everything is up to date .

0 0

Post a comment