Question

I have a fragment that has a send button.

On click of a send button, the activity is started to Choose an Email client from device.

Once we choose email client and sends the mail, it returns to the fragment again as expected.

But there is no need to have a fragment view as our mail sending task is finished.

So we want to come back to the previous activity after the mail is sent successfully.

How to do that?

I tried:

getActivity().getSupportFragmentManager().popBackStack();

But that doesn't worked.

My code on send button click is :

view.findViewById(R.id.sendbtn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
startActivityForResult(Intent.createChooser(email, "Choose an Email client :"),2);
getActivity().getSupportFragmentManager().popBackStack(); //this is not working to go back.
}
});
Was it helpful?

Solution

You can try to remove the fragment after you have send the mail(fixed):

getActivity().getSupportFragmentManager().beginTransaction().remove(MailFragment.this).commit();

But remember that it can be removed only if it was added dynamically using FragmentTransaction and the .add() method. If the fragment was added in XML, remove method won't work.

To add a fragment dynamically you should do this:

MailFragment mailFragment = new MailFragment(); 

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.containerForFragments, mailFragment).commit();

Then you can remove this fragment via the .remove() method.

By the way instead of removing the fragment you can try just hide it (will not be removed from memory):

 getActivity().getSupportFragmentManager().beginTransaction().hide(MailFragment.this).commit();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top