Finish parent and current activity in Android

Viewed 93379

I have 3 activities. Activity A which leads to activity B, which in turn can go back to activity A or start activity C. However, if I press back in activity C the app should close.

To sum up:

  • Activity A starts activity B
  • Pressing Back on activity B should lead to A
  • Activity B starts activity C
  • Pressing Back on activity C should close the app

How should I go from activity B to C? This code currently gives me a NullPointerException on the last line:

Intent intent=new Intent(ActivityB.this, ActivityC.class);
startActivity(intent);
ActivityB.this.finish();
ActivityB.this.getParent().finish();

If I switch the last two lines I also get a null pointer.

16 Answers

You can use finishAffinity() , it will close Current & all Parent Activities of the Current Activity.

Note : But any results from Child Activity to Parent Activity will not be handled.

Hope, it helps !!

You can just override the back key behavior:

Activity A starts activity B
Pressing Back on activity B should lead to A
Activity B starts activity C
Pressing Back on activity C should close the app

Note that I don't call super from onBackPressed. This also allows you to override the browse stack mechanism for Android, which I find to be a big advantage, since currently there doesn't seem to be a way to clear the single oldest item from the browse stack in a simple way.

public class B extends Activity
{
    ...
    @Override
    public void onBackPressed()
    {
        // Start activity A
        Intent aIntent = new Intent(this, A);
        startActivity(bIntent);
    }
    ...
}

public class C extends Activity
{
    ...
    @Override
    public void onBackPressed()
    {
        // Close
        finish();
    }
    ...
}

You can specifically finish the parent activity if needed too, but using this method, you don't have to worry about it.

Create instance of ActivityB.

on ActivityB.java

public static ActivityB instanceOfActivityB;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    instanceOfActivityB = this;
}

on ActivityC.java

void onClose() {
   ActivityB.instanceOfActivityB.finish();
   finish();
}

Hope it helps!

Related