Search code examples
androidandroid-intentandroid-activityonbackpressed

Android back button behaviour issue...


I have been using finish() for back button presses to go back to previous activity and its working fine but it is not working as expected for this specific scenario.

Here are a list of my activities and its functions:

Activity A - Show online forum topics

Activity B - Show the comments of a forum topic

Activity C - Post a new comment

After a user post a new comment, he will be directed to activity B.

Issue:

When i click on back button on Activity B, it will go back to Activity C, because it was my previous activity.

Activity A -> Activity B -> Activity C -> Activity B -> Activity C -> Activity B -> Activity A

Expectation

I want the user to go back to activity A from activity B at all cause.

Activity A -> Activity B -> Activity C -> Activity B -> Activity A

I tried using intent to only direct Activity B to A upon back pressed, but it is reloading the data on Activity A which i do not want.

Codes I tried:

case android.R.id.home:
            finish();
            return true;
//this works if i am only going back and forth one activity

case android.R.id.home:
 Intent i = new Intent(ActivityB.this, ActivityA.class);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            i.putExtra("forumLink", forumLink);
            i.putExtra("forumTitle", forumTitle);
            startActivity(i);
//this refreshes Activity A data

Solution

  • Call finish() on Activity C before going from C to B.

    You can make Activity A as parent of B ,and B as parent of C