Search This Blog

Wednesday 6 June 2012

How to finish the parent activity from child activity

finishing a parent activity  from child activity can be implement by starting the child activity using the startActivityForResult and implement the onActivityResult to process the result return by the child activity.

For Example if you have two activities ParentActivity and ChildActivity

Implement the following code in Parent Activity

/*start the child activity for a result*/

//bundle your stuff to pass data from parent activity to child activity

Bundle bundle = new Bundle();
bundle.putInt("category", 1);
Intent done = new Intent(ParentActivity.this, ChildActivity.class);
done.putExtras(bundle);
//start the activity for result
startActivityForResult(done,1);

Now implement the onActivityResult in parent activity

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
     super.onActivityResult(requestCode, resultCode, data);
     //matches the result code passed from ChildActivity
     if(resultCode == 0)
     {
                       //kill self
         ParentActivity.this.finish();
     }
}

Implement the following code in ChildActivity

@Override
    public void onStop()
    {
        super.onStop();
        this.setResult(0);
    }


@Override
    public void onDestroy()
    {
        super.onDestroy();
        this.setResult(0);
    }

Enjoy Creative Android Apps

2 comments: