Android Passing IntentExtra data to another activity

Pass data to another activity

In this tutorial, we will discuss how to navigate from one activity to another with IntentExtra data. Also to return to the first activity with a result data.

An android app user interface is made up of activities and fragments. At some point, you may need to navigate from one activity to another.

If this doesn’t make any sense, Follow along with the tutorial and you will get the idea.

What we are going to do

  • Create two activities
  • send data from the first activity to second activity
  • return data from the second activity to the first activity

Create two activities

Let’s start by creating a new project‌,

I’m creating a project with the name ActivityTransition (you can choose whatever you like).

In the project creation dialog, choose an empty activity and rename MainActivity to FirstActivity.

Make sure the launcher activity checkbox is checked for FirstAcivity. Then click finish and wait for it to finish building.

Now we need to create second activity and name it as SecondActivity. ‌

Creating a simple user interface

To get a simple user interface use the code below in the activity_main.xml.

and here is the code for second_activity.xml.

Navigating with IntentExtra data

Now you want to navigate from the first activity to second activity. With extra data.Copy the code below to

Paste the code inside the onCreate() method in the second activity. This is to fetch the passed data and show it as a toast.

Returning data to previous activity

If want to retrieve results in the first activity. that is to send data from second activity back to the first activity, use the startActivityForResult method instead of startActivity.

Then implement onActivityResultMethod() You can implement by pressing ctrl + O. then search for onactivityresult

Pass an intent code so that you can use it in onActivityResultMethod. Use below code instead of startActivity

Here is code for onActivityResult

And in SecondActivity add this code inside onCreate. So it can navigate back to the first activity with data. We are simply passing an email

Now if you run you should get something like this. All source code is found here

Leave a Reply

Your email address will not be published. Required fields are marked *