Step 10

Fill in the body of the onClick () method of the OnClickListener created in the last step.

This is the code that will be run when the user clicks on the confirm button. We want this to grab the title and body text from the edit text fields, and put them into the return Bundle so that they can be passed back to the Activity that invoked this NoteEdit Activity. If the operation is an edit rather than a create, we also want to put the mRowId into the Bundle so that the Notepadv2 class can save the changes back to the correct note.

1. Create a Bundle and put the title and body text into it using the constants defined in Notepadv2 as keys:

Bundle bundle = new Bundle();

bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString()); bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString()); if (mRowId != null) {

bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);

2. Set the result information (the Bundle) in a new Intent and finish the Activity:

Intent mIntent = new Intent(); mIntent.putExtras(bundle); setResult(RESULT_OK, mIntent); finish();

o The Intent is simply our data carrier that carries our Bundle (with the title, body and mRowId).

o The setResult() method is used to set the result code and return Intent to be passed back to the Intent caller. In this case everything worked, so we return RESULT_OK for the result code.

o The finish() call is used to signal that the Activity is done (like a return call). Anything set in the Result will then be returned to the caller, along with execution control.

The full onCreate() method (plus supporting class fields) should now look like this:

private EditText mTitleText; private EditText mBodyText; private Long mRowId; @Override protected void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); setContentView(R.layout.note edit); mTitleText = (EditText) findViewByld(R.id.title); mBodyText = (EditText) findViewByld(R.id.body); Button confirmButton = (Button) findViewByld(R.id.confirm); mRowId = null;

Bundle extras = getIntent().getExtras(); if (extras != null) {

String title = extras.getString(NotesDbAdapter.KEY_TITLE); String body = extras.getString(NotesDbAdapter.KEY_BODY); mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID); if (title != null) {

mTitleText.setText(title);

mBodyText.setText(body);

confirmButton.setOnClickListener(new View.OnClickListener()) {

public void onClick(View view) {

Bundle bundle = new Bundle();

bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());

bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());

bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);

Intent mIntent = new Intent(); mlntent.putExtras(bundle); setResult(RESULT_OK, mIntent); finish();

^ggj

Was this article helpful?

0 0

Post a comment