Finishing current activity from a fragment

Android

Android Problem Overview


I have a fragment in an activity that I am using as a navigation drawer. It contains buttons that when clicked start new activities (startActivity from a fragment simply calls startActivity on the current activity).

For the life of me I can't seem to figure out how I would finish the current activity after starting a new one.

I am looking to achieve something like this in the fragment:

@Override
public void onClick(View view) {
	// TODO Auto-generated method stub
	if (view == mButtonShows) {
		Intent intent = new Intent(view.getContext(), MyNewActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	} 
}

But it seems Fragment.class does not implement finish() (like it implements startActivity(...)).

I would like the activity backstack cleared when they launch the 2nd activity. (so pressing back from the new activity would technically drop them back to the launcher)

Android Solutions


Solution 1 - Android

When working with fragments, instead of using this or refering to the context, always use getActivity(). You should call

Java

getActivity().finish();

Kotlin

activity.finish()

to finish your activity from fragment.

Solution 2 - Android

Well actually...

I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html

Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.

Solution 3 - Android

As mentioned by Jon F Hancock, this is how a fragment can 'close' the activity by suggesting the activity to close. This makes the fragment portable as is the reason for them. If you use it in a different activity, you might not want to close the activity.

Code below is a snippet from an activity and fragment which has a save and cancel button.

PlayerActivity

public class PlayerActivity extends Activity 
    implements PlayerInfo.PlayerAddListener {

    public void onPlayerCancel() {
       // Decide if its suitable to close the activity, 
       //e.g. is an edit being done in one of the other fragments?
       finish();
    }
}

PlayerInfoFragment, which contains an interface which the calling activity needs to implement.

public class PlayerInfoFragment extends Fragment {
   private PlayerAddListener callback; // implemented in the Activity

   @Override
   public void onAttach(Activity activity) {
     super.onAttach(activity);
     callback= (PlayerAddListener) activity;
   }

   public interface PlayerAddListener {
       public void onPlayerSave(Player p); // not shown in impl above
       public void onPlayerCancel();
   }

   public void btnCancel(View v) {
      callback.onPlayerCancel(); // the activity's implementation
   }
}

Solution 4 - Android

You should use getActivity() method in order to finish the activity from the fragment.

getActivity().finish();

Solution 5 - Android

In Fragment use getActivity.finishAffinity()

getActivity().finishAffinity();

It will remove all the fragment which pushed by the current activity from the Stack with the Activity too...

Solution 6 - Android

This does not need assertion, Latest update in fragment in android JetPack

requireActivity().finish();

Solution 7 - Android

Every time I use finish to close the fragment, the entire activity closes. According to the docs, fragments should remain as long as the parent activity remains.

Instead, I found that I can change views back the the parent activity by using this statement: setContentView(R.layout.activity_main);

This returns me back to the parent activity.

I hope that this helps someone else who may be looking for this.

Solution 8 - Android

Very simple...

1- just grab activity by getActivity() in the fragment

2- then call finish();

So just getActivity().finish(); will finish the parent activity.

Solution 9 - Android

Try this. There shouldn't be any warning...

            Activity thisActivity = getActivity();
            if (thisActivity != null) {
                startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
                thisActivity.finish();
            }

Solution 10 - Android

You have two options for Java and Kotlin. However, logic of both ways are same. You should call activity after call finish() method.

> Answer for Kotlin,

If your activity cannot be null, use Answer_1. However, if your activity can be null, use Answer_2.

Answer_1: activity!!.finish()
Answer_2: activity?.finish()

> Answer for Java,

getActivity().finish();

Solution 11 - Android

Simple solution:

activity?.finish()

Solution 12 - Android

To finish activity in a Fragment use:

getActivity().finish();

Solution 13 - Android

try to use this

yes Fragment.class does not implement finish()

When working with fragments, instead of using this or refering to the context, always use getActivity(). You should call

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNPikeView Question on Stackoverflow
Solution 1 - Androidcoder_For_Life22View Answer on Stackoverflow
Solution 2 - AndroidJon F HancockView Answer on Stackoverflow
Solution 3 - AndroidSasquatchView Answer on Stackoverflow
Solution 4 - AndroidMadhu JayaramaView Answer on Stackoverflow
Solution 5 - AndroidTousif AkramView Answer on Stackoverflow
Solution 6 - AndroidrahatView Answer on Stackoverflow
Solution 7 - AndroidDave CoxView Answer on Stackoverflow
Solution 8 - AndroidAli NawazView Answer on Stackoverflow
Solution 9 - Androidsam byteView Answer on Stackoverflow
Solution 10 - AndroidNamelessView Answer on Stackoverflow
Solution 11 - AndroidMalik Shahbaz ZafarView Answer on Stackoverflow
Solution 12 - AndroidAkash JaiswalView Answer on Stackoverflow
Solution 13 - AndroidRahul GoswamiView Answer on Stackoverflow