Learn How to switch or navigate between activities and how to pass data to Activity in android studio

In this article, we will look at how we can switch between activities or how we can navigate from one activity to another. we will learn about Intents , How to use intents to start an activity and how we can pass data with intents etc. please read the full article


As a developer when you are designing an android application you might need to add so many activities that you would like to use for different screens within your android application. Most of the time we also need to switch between various activities to perform different actions so in this article we will learn to switch between activities and will also see how we can pass data to an activity. for better understanding we recommend you to watch the above video tutorial in which we explained each and everything in a very simple way so that you can understand it easily.

Procedures on how to switch between activities in android

  • You should create your required activities.
  • The activities should be added to the manifest.xml file (at times it is mostly done programmatically by the android studio).
  • Inside the current activity, you should create an intent that will take you to the other activity you intend to switch to.
  • The next you should do is to add startActivity(i) method to go to the other activity you want to switch to (“i” in the code stands for the intent you want to switch to).
  • The last step is that you need to add a back button on the other activity that will be used to call the finish method on the activity after pressing the back button.

How to transition between activities in android

You should Create two Activities

The first thing you should do is to create about two activities which we are going to be using for this tutorial. You should name the first activity as FirstActivity and the second one should be named as SecondActivity.
Inside the FirstActivity XML file, you should add a TextView to display “First Activity” and the next thing to do is to also add a Button containing a text of “Go To SecondActivity” for easy layout design you should use Constraint layout as we used in this example.

see the following code for reference.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="@android:color/holo_red_dark"
    android:layout_height="match_parent"
    tools:context=".FirstActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activity First!"
        android:textColor="@android:color/white"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Go to Second Activity"
        android:onClick="goToSecondActivity"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintStart_toStartOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView" />


</androidx.constraintlayout.widget.ConstraintLayout>

after adding the above code in your FirstActivity XML file your layout design will look something like this.


Just like you did for the first activity let’s do the same for the second one. Inside SecondActivity you should add a TextView to display “Second Activity” and the next thing to do is to also add a Button containing a text of “Go to FirstActivity”, same for this activity; for easy layout design, you should use Constraint layout 

SecondActivity XML File Code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="@android:color/holo_green_dark"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activity Second!"
        android:textColor="@android:color/white"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Go to First Activity"
        android:onClick="goToFirstActvity"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintStart_toStartOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView" />


</androidx.constraintlayout.widget.ConstraintLayout>

Bellow, you can see the second activity XML Design. we set different colors for both activities so we can identify them easily.


 

Check your app manifest.xml

If the two activities have not been added to the manifest.xml you have to add them manually. But in most cases, if you are using the android studio to create the two activities they will be added to the manifest automatically. But you have to check to confirm in any case.

Set onClickListner on both activities buttons. 

as you can see we added a button in both activities. we will set onClickListner on each button to handle user clicks we will write activity switching code inside that onclickListner method.  bellow you can see the button code that we have added inside the second activity XML file

<Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Go to First Activity"
        android:onClick="goToFirstActvity"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintStart_toStartOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

if you look at the above button code you will also see the android:onClick attribute and we set the value "gotToFirstActivity" this value basically is a method name that we must have to create in Second Activity Java file otherwise you will see an error. here basically we are setting click listener on this button whenever a user will click on this button goToFirstActivity method will be called. 

Create goToFirstActivity method inside Second Activity Java file.

   public void goToFirstActvity(View view) {
    
    }

Next Is Creating The Intent And Starting The Activity

For Switching Between activities, we used Intents. To create an object of Intent we provide current activity context and targeted activity class name like below.

Intent intent = new Intent(Context,NextActivity.class);

 and then we call startActivity(intent) 

Complete code of goToFirstActivity Method

  public void goToFirstActvity(View view) {
        Intent intent = new Intent(SecondActivity.this,FirstActivity.class);
        startActivity(intent);
        finish();
    }

Now, whenever a user will click on the second activity button above method will call and this method will take the user from SecondActivity to FirstActivity this way you can easily switch from SecondActivity to FirstActivity now if you want to switch from FirstActivity to second then simply repeat the same steps that we have discussed above,  we also called finish();  inside the above method.  it's basically used to destroy the current activity. after calling finish current activity will not keep in back stake 

Passing data between activities

As you can switch between multiple activities is also possible for you to transfer data or share data from one activity to another using the putExtra…() method. For example, if you want to pass a string value you should use the putExtra(“key”,  “value String”) in the current activity while in the activity you want to switch to you should the getStringExtra(“key”) to receive the data sent. In the case of an in integer value; if you want to pass an integer value you should use the putExtra(“key”,  int value) in the current activity while in the activity you want to switch to you should the getIntExtra(“key”, default value) to receive the data sent. But take note for the default value in the case of an integer can be 0 or null (for example getIntExtra(“key”, 0) or getIntExtra(“key”, null)).
From the above example you can use in the case of a quiz application after finishing the quiz you will like to display the grade, comment, score, and other things related to that in the next activity which can be the ResultActivity. I have explained above how to pass and receive the string values and also how to pass and receive the integer values. Which this explanation you can do many things using this method.


Definition of Intent in Android

The intent is used in requesting actions within app components for example we have the broadcast receivers, activities, and services. 

Uses of Intents

  • Broadcast delivering
  • Used to start an activity
  • Used to start a service

Intents exist in two forms basically; we have Implicit and Explicit intents. The implicit intent can be used for example when your app cannot do a particular action but can be done by other apps you might want the user to choose the app that will be used. The Explicit intent is used to launch an app component; for example, launching a specific activity.

Conclusion 

In this article, I have discussed how you can easily switch between activities in android. There is a great advantage in doing this because you will reserve the back button functionality as well as minimizing some errors which might occur since you might be working with multiple activities.

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
1