Moving to previous fragment from activity

42
January 12, 2019, at 10:20 PM

I have three fragments in the app. I am creating, call them f1,f2, f3. All these are contained in the MainActivity. In the third fragment f3, I have a button which takes a user to an activity where they can post a picture. Now whenever the post is successful (using onSuccessListener), I am displaying a toast message and thereafter taking the user to the MainActivity using intent.

Everything works fine, but I wanted to take the user to the previous fragment f3, rather than the MainActivity which launches with fragment f1. How can I achieve this?

Here is what I've tried so far:

@Override
public void onBackPressed(){
    finish();
}

// didnt work

Here is the current code that am using

//my other code

PostsRef.child(current_user_id + timesfm).updateChildren(postsMap)
                        .addOnCompleteListener(new OnCompleteListener() {
                            @Override
                            public void onComplete(@NonNull Task task)
                            {
                                if(task.isSuccessful())
                                {
                                    Toast.makeText(PostActivity.this, "Post updated.", Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                    SendUserToMain();
                                }
                                else
                                {
                                    Toast.makeText(PostActivity.this, "Error Occured.Please try again.", Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                }
                            }
                        });
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
private void SendUserToMain() {
    Intent mIntent = new Intent(PostActivity.this, MainActivity.class);
    mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(mIntent);
}
Answer 1

Your problem is that instead of finish() in your PostActivity, in order to return to the original MainActivity instance, you launch a new instance with your method

private void SendUserToMain() {
    Intent mIntent = new Intent(PostActivity.this, MainActivity.class);
    mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(mIntent);
}

Instead of doing that, just do:

private void SendUserToMain() {
    finish();
}

in order to finish the PostActivity and return to your original MainActivity instance. Of course, this means that you'll also NOT finish your MainActivity when you're first going to the PostActivity()!

// Sample method of you launching PostActivity, I don't know your actual implementation
void sendUserToPostActivity() {
    Intent mIntent = new Intent(MainActivity.this, PostActivity.class);
    startActivity(mIntent);
    // finish() <-- Don't do that, so your MainActivity remains in the backstack
}

If you want something more sophisticated, like adding a result to your return, you can also do the startActivityForResult -> setResult routine as described by other people.

Answer 2

Instead of using startActivity(intent) from your fragment use startActivityForResult(intent,requsetCode) in our fragment and use setReult(requestCode) and finish() methods in your target activity.

Answer 3

All you need to do instead of calling SendUserToMain(); is call finish() as the previous Activity with the last fragment state is on the backstack. At the moment in your SendUserToMain(); method is creating a new instance of MainActivity which will call its onCreate() method and set up the Activity as if it were new (which it is).

Answer 4

Code Credit: Nishant

You can use startActivityForResult(). From your MainActivity start PostActivity and don't finish MainActivity:

Intent intent = new Intent(this, PostActivity.class);
startActivityForResult(intent , 10);
// don't finish..

Now when you are done in your PostActivity go to MainActivity this way:

private void SendUserToMain() {
    Intent intent = new Intent();
    intent.putExtra("frag",3);
    setResult(Activity.RESULT_OK,intent);
    finish();
}

Now in your MainActivity:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 10) {
        if(resultCode == Activity.RESULT_OK){
            int fragment = data.getIntExtra("frag");
            if (fragment == 3){
                // go to f3
            }
        }
    }
}
Answer 5

Thanks a lot for your help guys, y'all are so kind. So with the help of @Ore, I finally figured out where the problem was. Turns out while calling PostActivity from my fragment f3, I'd also called the finish method after the intent. Here is what Id done

private void SendUserToPostActivity() { Intent addPostIntent = new Intent(getActivity(), NewPost.class); addPostIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(addPostIntent); getActivity().finish(); }

The correct one should be

private void SendUserToPostActivity(){
Intent addPostIntent = new Intent(getActivity(), NewPost.class);

startActivity(addPostIntent); }

then to navigate back to the latest fragment, f3, I called the finish() method.

@Ore explains it better Thanks everyone for your input though. Really appreciated!

READ ALSO
How to hook photo call api on android?

How to hook photo call api on android?

I have an APK which taking photos once Button "Take Photo " clickedAPP pop-up photo api and taking picture

34
Scroll Recycleview to Top position when activity starts using Linearlayoutmanager

Scroll Recycleview to Top position when activity starts using Linearlayoutmanager

I"m retrieving Firebase RealTime Database to my Recycleview Adapter ClassI want to sort the data by date with latest post at top

22
Is there a way to visualize how a fragment would look like when it&#39;s loaded in adnroid studio inspector?

Is there a way to visualize how a fragment would look like when it's loaded in adnroid studio inspector?

I'm making an android app that has a couple of fragments in itI was wondering if you could look at how your fragments would look like when they are loaded in the layout inspector

41
xamarin android resource management

xamarin android resource management

I had a newly created Xamarin Android native app and was trying to display a three dots icon for popup menu (⋮)Using this xml it worked

47