Search code examples
androidandroid-fragmentsandroid-intentandroid-activity

Close opened activity, so main activity can update fragment without state loss in Android


I currently have two activities, the first one which is called when the app is opened, EventsActivity , and the second one which comes from EventsActivity called EventActivity. If EventActivity is opened during a notification, which I process through EventsActivity within an onIntent, there is a state loss error because EventActivity is open. How can I close EventActivity before updating my fragment in EventsActivity.

Launch EventActivity from EventsActivity

public void launchEvent() {
    Intent intent = new Intent(this, EventActivity.class);
    startActivity(intent);
}

Update View Based On Notification From EventsActivity (EventActivity Is Opened)

@Override
    public void onNewIntent (Intent intent)
    {
FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = manager.beginTransaction();
            fragmentTransaction.replace(R.id.content_frame, new MessageFragment());
        manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); // <!-- state loss exception
    fragmentTransaction.commit();
    }

Solution

  • You need to call super.onNewIntent(intent) to tell the FragmentManager that it is safe to do Fragment transactions.

    @Override
    public void onNewIntent (Intent intent)
    {
        super.onNewIntent(intent);
        FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = manager.beginTransaction();
            fragmentTransaction.replace(R.id.content_frame, new MessageFragment());
        manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        fragmentTransaction.commit();
    }