Wednesday, February 25, 2009

Android 101: Launching dialogs - part 2

So, we went over a simple method of getting user data from a dialog last time, now let's get a little more complicated.  In lots of situations, getting one piece of data per dialog isn't good design.  Wouldn't it be great if we could package a bunch of data together and move it between dialogs as a single unit?  Before we get into data passing, though, let's take a step back and quickly touch on how to launch a dialog.  Last time, we used an AlertDialog.  That's good for a quick popup, and getting a boolean-style answer, but it's not meant for really anything else.  Most of the time, it's best to subclass Activity.  If you're just looking to launch a dialog and don't need to get a result, it can easily be done like this:
Intent custom = new Intent(this, MyDialog.class);
On the other hand, when you want to do something (such as get data from the dialog) after it closes, it gets called like so:
Intent custom = new Intent(this, MyDialog.class);
When the dialog is finished collecting information, it fires the calling class's onActivityResult().  The call signature is simple enough:
protected void onActivityResult(int requestCode, int resultCode, Intent data);
The key piece we care about right now is that Intent.  What's in there?  That depends on what that dialog did.  Let's say the dialog took a String input which is meant to be given to the calling method.
// Package up the relevant data for the calling method
Bundle bundle = new Bundle();
bundle.putString("question", question);
Intent returnIntent = new Intent();
// Insert the data into the Intent that gets passed to onActivityResult()
setResult(RESULT_OK, returnIntent);
// Close the dialog
As you can imagine, unpacking is basically the reverse of packing, and it goes in onActivityResult(), as I mentioned earlier:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
Bundle extras = data.getExtras();
String question = extras.getString("question");
// use the data here
Notice the use of a string key.  I don't like putting hard-coded strings in code - they're bad for internationalization and belong in strings.xml.  But since these strings don't normally end up displayed to the user, there's no need for internationalization, so hard coding is easier to write and faster at runtime.    Anyway, be sure to use matching keys. So, that's all for part 2.  Drop me a line if there's a particular topic you'd like to hear about.  Happy coding!


Anonymous said...

Very clear! Thank you.

Anonymous said...

Very clear and helpful! Thank you.