Wednesday, June 13, 2012

Android - Refresh Parent Activity and Dialog (Activity) Results

When you're working with Android activities, sometimes you'll want to keep a 'parent' activity or main activity running instead of closing it with this.finish(). When you have this kind of activity, you also often want to refresh it when the child activity is complete.

This is the problem I ran into - I found that after I completed the 'child' activity, I didn't know what events were available for the parent activity to refresh.

The way I was starting the child activity was by using this.startActivity, like this:

Intent i = new Intent(PARENT_ACTIVITY.this, CHILD_ACTIVITY.class);
PARENT_ACTIVITY.this.startActivity(i);


But if you do start the activity this way:

Intent i = new Intent( PARENT_ACTIVITY.this,  CHILD_ACTIVITY.class);
startActivityForResult(i, 0);

Then you can implement a method when the result is returned. The integer, in this case 0, helps you keep track of where you started the activity. Use a different constant value (or enum) for each type of activity you launch so you can easily keep track of it.

Here's a simple sample of the method you need to implement:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
refresh();
}
 That's it!

Also, you can look at the Intent and resultCode to get more information about what happened in the Activity. In the child activity, you have to call setResult(int) so it knows what resultCode to use. For more information about using onActivityResult like a 'DialogResult', visit Android's documentation on starting activities.

Also, if you don't have a 'parent' activity relationship, always remember to call this.finish() before starting an activity. Here's how I normally start an activity and end the current one:


        CURRENT_ACTIVITY.this.finish();
        Intent i = new Intent( CURRENT_ACTIVITY.this, NEXT_ACTIVITY.class);
        CURRENT_ACTIVITY.this.startActivity(i);



0 comments:

Post a Comment

Comments (and links to your site) are welcome, but please provide valuable input. "Great blog!" posts with links will be deleted.