How to Go Back to Previous Activity in Android?

In this article, we are going to see how we can add a back button to an activity through which we can go back to its previous activity. This can be achieved with just a few lines of code, which is explained in the steps below
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Working with the activity_main.xml File
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Next Activity"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout> | 
Step 3: Create a New Activity
In the projects folder, right-click on app > new > Activity > Empty Activity. You can customize this activity accordingly.
Step 4: Working with MainActivity File
We now add an onClickListener in the MainActivity to trigger whenever the button is clicked and set up an Intent inside it.
Java
import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {       // create Button object         Button button;           @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                   // give reference to the Button view whose id is button         // and give it to the Button instance created above        button = findViewById(R.id.button);                   // setting onClickListener        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                // create an intent to switch to second activity upon clicking                Intent intent = new Intent(MainActivity.this,SecondActivity.class);                startActivity(intent);            }        });    }} | 
Kotlin
import android.content.Intentimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {         // create Button object    private lateinit var button: Button         override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)                 // give reference to the Button view whose id is button        // and give it to the Button instance created above        button = findViewById(R.id.button)                 // set onClickListener        button.setOnClickListener(View.OnClickListener {            // create an intent to switch to second activity upon clicking            val intent = Intent(this, SecondActivity::class.java)            startActivity(intent)        })    }} | 
Step 5: Checking AndroidManifest.xml
Navigate to app > manifest > AndroidManifest.xml
Step 6: Check Parent Attribute
Inside Android Manifest File, Check if SecondAcitvity has been added or not, and then add a new attribute of parentActivityName and set it to MainActivity as shown below.
XML
<?xml version="1.0" encoding="utf-8"?>    package="com.gfg.android.gfgapp">    <application        android:allowBackup="true"        android:dataExtractionRules="@xml/data_extraction_rules"        android:fullBackupContent="@xml/backup_rules"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/Theme.GFGApp"        tools:targetApi="31">                 <!-- Shall be automatically added after creating new activity.            If not, add the following code snippet -->        <activity            android:name=".SecondActivity"            android:exported="false"            android:parentActivityName=".MainActivity"/>        <!-- till here -->                 <activity            android:name=".MainActivity"            android:exported="true">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest> | 
Now run the Application. In the second activity, the back button at the top left can be used to go back to the previous activity.
				
					


