Open In App

Understanding Activity Lifecycle to Retain UI Data when Back Pressed in Android

Last Updated : 28 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

What is onBackPressed() in Android?

This is an override function called when the user presses the back button on an Android device. It has great implications on the activity lifecycle of the application. The official documentation states that onBackPressed() method is called when the activity has detected the user’s press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

So, through this article, we will show you how you can override this method and retain the activity data. But before that, it is necessary to understand the Activity Lifecycle in Android. Refer to this article for a better understanding of the Activity Lifecycle in Android: Activity Lifecycle in Android with Demo App.

This article has 4 parts:

  1. Create a template code to understand the navigation key events and linked Activity Lifecycle methods (Skip if you know Activity Lifecycle)
  2. Override the on back pressed method
  3. Testing EditText
  4. Testing TextView

1. Create a template code to understand the navigation key events and linked Activity Lifecycle methods

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. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Override all the methods in Activity Lifecycle

We implemented a Toast message in every method to understand which method is called when during the Activity Lifecycle. Now simply run the project on a device or an emulator.

Kotlin




class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        Toast.makeText(applicationContext, "onCreate", Toast.LENGTH_SHORT).show()
          
        }
    }
  
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext, "onPause", Toast.LENGTH_SHORT).show()
    }
  
    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext, "onStop", Toast.LENGTH_SHORT).show()
    }
  
    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext, "onDestroy", Toast.LENGTH_SHORT).show()
    }
  
    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext, "onRestart", Toast.LENGTH_SHORT).show()
    }
  
    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext, "onStart", Toast.LENGTH_SHORT).show()
    }
  
    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext, "onResume", Toast.LENGTH_SHORT).show()
    }
}


Step 3: Run the program

  1. When the application starts: onCreate, onStart, onResume
  2. When App Overview Button is pressed: onPause, onStop
  3. When Home Button is pressed: onPause, onStop
  4. When Back Button is pressed: onPause, onStop, onDestroy

Output:

Observation:

We can see that in any case other than the back press, the activity is stopped. Basically, it is not destroyed and data is retained. However, when the back button is pressed, the activity is destroyed, meaning, the temporary data is lost during this call. This is what the official documentation states.

But we do not want to lose this data. To retain the data, we need to override the back pressed method. Back pressed method by nature destroys the activity. We will make changes in such a way that the activity will stop but not destroy. Continue reading.

2. Override the on back pressed method

Please read the comments in the code.

Kotlin




class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        Toast.makeText(applicationContext, "onCreate", Toast.LENGTH_SHORT).show()
    }
  
    // Overriding onBackPressed method
    override fun onBackPressed() {
        
        // Implement this method to stop
        // the activity and go back
        this.moveTaskToBack(true)
    }
  
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext, "onPause", Toast.LENGTH_SHORT).show()
    }
  
    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext, "onStop", Toast.LENGTH_SHORT).show()
    }
  
    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext, "onDestroy", Toast.LENGTH_SHORT).show()
    }
  
    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext, "onRestart", Toast.LENGTH_SHORT).show()
    }
  
    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext, "onStart", Toast.LENGTH_SHORT).show()
    }
  
    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext, "onResume", Toast.LENGTH_SHORT).show()
    }
}


Output:

Now we can observe that on the back press, the activity will stop but not destroy. We shall now implement some UI for testing if this actually works. Keep reading.

3. Testing EditText

Step 1: Add EditText in the layout file (activity_main.xml)

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <EditText
    android:id="@+id/et1"
    android:layout_width="match_parent"
    android:layout_height="50sp"
    android:textSize="25sp"
    android:inputType="text"
    android:layout_centerInParent="true"/>
  
</RelativeLayout>


For testing the EditText, we need not code anything in the main code other than what is specified in the previous (Override the on-back pressed method) code.

Input:

Type anything in the EditText and press the back button. Return back to the app and you will notice that text is retained in the EditText bar.

Output:

The text in the EditText is retained. This means our method works fine. We shall now test it on a TextView. Keep reading.

4. Testing TextView

Step 1: Add a TextView and a Button in the layout file (activity_main.xml)

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click the button"
        android:textSize="40sp"
        android:layout_centerInParent="true"/>
  
    <Button
        android:id="@+id/btn1"
        android:layout_below="@id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click"
        android:layout_centerHorizontal="true"/>
  
</RelativeLayout>


Step 2: Add functionality to these elements via the main code (MainActivity.kt)

Kotlin




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        Toast.makeText(applicationContext, "onCreate", Toast.LENGTH_SHORT).show()
  
        // TextView and Button
        val tv1 = findViewById<TextView>(R.id.tv1)
        val btn1 = findViewById<Button>(R.id.btn1)
          
        // A code to increment a variable and 
        // display it on TextView on Button Click
        var k = 0
        btn1.setOnClickListener {
            tv1.text = k.toString()
            k++
        }
    }
  
    override fun onBackPressed() {
        this.moveTaskToBack(true)
    }
  
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext, "onPause", Toast.LENGTH_SHORT).show()
    }
  
    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext, "onStop", Toast.LENGTH_SHORT).show()
    }
  
    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext, "onDestroy", Toast.LENGTH_SHORT).show()
    }
  
    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext, "onRestart", Toast.LENGTH_SHORT).show()
    }
  
    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext, "onStart", Toast.LENGTH_SHORT).show()
    }
  
    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext, "onResume", Toast.LENGTH_SHORT).show()
    }
}


Input:

Keep clicking the button, the number in TextView will keep incrementing. Now try the back button and open the app again. The text is retained in the TextView.

Output:

Our method works perfectly fine. Now use this method in your codes to retain the activity data.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads