How to clear the back stack in Android?


Introduction

Many times in android applications we use to display so many different types of activities. These activities are used in android applications for performing the different tasks. When we are navigating from one activity to another activity, the previous activity from which we have navigated remains in the stack, which will take system memory and may degrade the performance of the application. To prevent this we have to clear the activity history stack of an android application. In this article we will take a look on How to clear the back stack in Android.

Implementation

We will be creating a simple application in which we will be creating two activities. When a user will navigate from one activity to another activity we will be clearing the back stack of an activity so that when the user presses back from the second activity he will exit from the app instead of going back to the previous activity.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 3 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/idRLLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- text view for displaying  heading of the application -->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@id/idBtnOpen"
      android:layout_marginStart="10dp"
      android:layout_marginTop="100dp"
      android:layout_marginEnd="10dp"
      android:padding="5dp"
      android:text="How to Clear Back Stack in Android"
      android:textAlignment="center"
      android:textAllCaps="false"
      android:textColor="@color/black"
      android:textSize="18sp"
      android:textStyle="bold" />
  
   <!-- on below line we are creating a button to post the data -->
   <Button
      android:id="@+id/idBtnOpen"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_margin="20dp"
      android:text="Open new activity"
      android:textAllCaps="false" />
</RelativeLayout>

Explanation − In the above code we are creating a Relative layout as a root layout and inside that we are creating a simple text view in which we are displaying the heading of our application. After this text view we are creating a simple button. Inside the on click of this button we will be opening our second activity.

Step 4 : Creating a new activity

For displaying a second activity, we will be creating a new activity. For creating a new activity we have to navigate to app>Right click on it>New>Activity>Empty Activity and then specify the activity name as SecondActivity and click on Finish to create a new activity. Now your activity will be created.

Step 5 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.androidjavaapp;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.toolbox.HttpClientStack;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

   // on below line creating a variable for button and edit text.
   private Button openActivityBtn;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // on below line we are initializing variables.
      openActivityBtn = findViewById(R.id.idBtnOpen);

      openActivityBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            
            // on below line we are creating a new intent.
            Intent i = new Intent(MainActivity.this, SecondActivity.class);
            
            // on below line adding a flag for our activity to clear the history stack.
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            
            // on below line calling a method to start the activity
            startActivity(i);
            
            // on below line calling finish to close the current activity.
            finish();
         }
      });

   }
}

Explanation − In the above code we are creating variables for our button. After that we can get to see the onCreate method. This is a default method in our MainActivity.java file which is used to load the activity_main.xml file of our application. Inside this onCreate method we are initializing the variable for the button with the id which we have given in our activity_main.xml file. After initializing our variable we are adding a click listener for our button. Inside the click listener for our button we are opening a new activity through intent and lastly we are calling the finish method to remove the current activity from the history stack and open the new activity as SecondActivity.

Step 6 : Working with activity_second.xml

Navigate to activity_second.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_second.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".SecondActivity">

   <!-- on below line creating a text view for displaying a heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Welcome to Second Activity"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />
</RelativeLayout>

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Inside our application when we click on a button to open a new activity, we can get to see our new activity has opened but at the same time we have cleared the current activity from our activity back stack. When we press back from the second activity our app is getting closed. This is because we have removed the MainActivity from our activity back stack.

Conclusion

In this article we have taken a look on How to clear the back stack in Android. Along with that we have taken a look on How to implement it within our android application.

Updated on: 30-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements