Search code examples
javaandroidandroid-intentonbackpressed

Have to press the back button twice to get to previous activity?


I am simply trying to click back and navigate to my previous activity. My flow is this: I go to news_feed activity -> Comments activity -> User Profile activity -> click back (Go to Comments activity) -> click back (This does nothing for some reason) -> Click back (Go back to news_feed activity). I'm not sure why I have to click back twice when I try to go from Comments activity back to news_feed activity. If I go from news_feed activity -> Comments -> press back (Go to news_feed activity) this works perfectly. Here is my code:

news_feed.java:

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
}

Comments.java:

@Override
public void onBackPressed() {
    super.onBackPressed();
    this.finish();
}

UserProfile.java:

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(UserProfile.this, Comments.class);
    Bundle bundle = new Bundle();
    bundle.putString("postId", postId);
    bundle.putString("posterUserId", posterUserId);
    bundle.putString("posterName", posterName);
    bundle.putString("postStatus", postStatus);
    bundle.putString("postTimeStamp", postTimeStamp);
    bundle.putString("postTitle", postTitle);
    intent.putExtras(bundle);
    startActivity(intent);
    finish();
}

I don't think navigating to these activities would change anything, but I can include the intents that I used to navigate to these activities also if necessary. Otherwise I just included the onBackPressed code that I had for these activities. Any ideas why this might cause a problem? Any help would be appreciated. Thanks.


Solution

  • In your UserProfile class, in onBackPressed() method, you are starting the Comments class again. Why do you have to do this? What is happening is, you are starting a new Comments activity onBackPressed() of the USerProfile class, so there are two instances of Comments Activity. So you feel you are pressing back btn twice.

    If you have to pass data back to Comments from UserProfile class, then make use of setResult() method.

    This will be of help

    How to pass data from 2nd activity to 1st activity when pressed back? - android

    Sending data back to the Main Activity in android