Intents – 3

How to Pass Data between Activities using Intents

Hello World! In this post, we’re going to learn how we can pass data back and forth between two different activities. We’ll also learn how to reuse layouts and use our app’s manifest with Intents. The Intent object is the fundamental class that we use to pass data around in Android. It acts as a container of information to the system that we can manipulate. We’re going to see how we can transfer to an Activity and get a result back from that Activity as well.

Note: To make this easier on us, we’re going to use source code from a previous post on Toolbars so if you have any questions as to the specifics of ListViews or Toolbars, please read those respective articles!

We’re going to be building an app that displays a list of countries, and, when the user taps on an entry, it brings them to another view that simply displays the name of the country. The interesting part is that the second Activity will receive the country to display from the first Activity.

Let’s create a new Android Studio project and call it IntentDemo. We’re going to start by adding the following to the res/values/strings.xml file to act as our database backend.

Now, before we make changes to our view, since we’re going to need a Toolbar in both Activity’s views. Instead of copying and pasting code from one file to another, we can declare a layout file that can be inserted in both views. This way, we only need to edit one layout file, not every single one! Let’s right-click on the res/layout folder and create a new layout file whose name toolbar and whose root element is android.support.v7.widget.Toolbar . Now we add properties to this toolbar like so.

Since we’ve created this layout file, we can insert it into any number of other layout files as well. For example, let’s go into the activity_main.xml file and insert the following.

In the above code snippet, we can insert the contents of the toolbar layout into this layout by using the include tag and layout attribute. Let’s first have our list configured before we move on to create another Activity. Open up the MainActivity class and add the following code snippet to set up our list.

You’ll notice that we can access the Toolbar even when it’s actually in another file thanks to the include tag. The call to setSupportActionBar(Toolbar)  simply sets this Toolbar to act as the system Toolbar; we’ll see more of this when we get to the other Activity. In the final line, we’re using the overload of the setTitle(int)  that accepts a string resource ID. We’ll be forced to implement the interface that will add the onItemClick(...)  method, but we can leave that empty for now. Run the code now and verify that you get a list of countries as a start.

Intents – 1

Now we’re ready to create a new Activity. There are several steps involved in this process: creating the Java class, creating the XML layout, and registering the Activity with the app manifest. Luckily, Android Studio can do all of this for us with a single wizard! Right-click on the package name of our MainActivity and go to New → Activity → Empty Activity. We’ll call ours DetailActivity and Android Studio will create the corresponding layout file and register it with the app manifest. Let’s first look at the layout and replace it with the following.

We’re just simply declaring a TextView that will display our country. We need a top-level LinearLayout so that the Toolbar appears first. Then we use the include tag to insert the Toolbar into this layout. We need a RelativeLayout after the Toolbar so that the TextView is centered on the screen. Now we can go back to our MainActivity and start the other Activity when a list item was clicked. Let’s add the following code to the onItemClick(...)  method. We also need some constants to keep track of uniqueness so we’ll add those as fields at the top of the Activity.

In this code snippet, we’re creating a new Intent object, giving it some data, and starting up the other Activity. The first parameter to the constructor is the Context and the second is the class we want to start. Each class in Java has a class property that uses Java’s Reflection API (where a program can know about itself so to speak). This particular parameterized constructor uses Java Reflection to launch the appropriate Activity. In the next line, we call a method to store the country into the Intent with a unique String ID. We’ll retrieve this value later in the other Activity. Then, we call the method to start the other Activity through the Intent. Since we want a response back, we’re also passing in a unique request code that we’ll be checking later. Now let’s open up the DetailActivity and add the following code in the onCreate(Bundle)  method.

In the very first line, we grab the String hidden away in the Intent. We need the unique ID to grab it however. Then we set the TextView’s text to be that country. We grab the Toolbar and set the system’s ActionBar to be this Toolbar. The reason for this is so we can provide backwards-navigation for the user to get back the the previous Activity. You might have noticed in other apps that it looks like a left-facing arrow to the left of the Toolbar’s title. Instead of having to import and manage that image, we can have the system display that for us by getting the ActionBar, in other words our Toolbar, and tell the system to display that backwards-navigation icon. We just have to make sure we implement the callback. We set this callback when we call setNavigationOnClickListener(...) . This will force us to implement an interface and a callback method.

Before we do this, we need to tell Android that the parent activity of DetailActivity is MainActivity. We can only do this in our app’s manifest file. In our Project view, let’s open up the app/manifests/AndroidManifest.xml file and find and replace the tag relating to DetailActivity with the following.

The above code snippet tells Android that the parent activity of DetailActivity is MainActivity. Now that we’ve done this, we can go back to our DetailActivity and configure the navigation. To do this however, we’ll need an extra constant to do the same task as EXTRA_COUNTRY did in MainActivity.

We’re creating a new Intent object and putting in a small verification message. This method setResult(...)  will be helpful when we go back to MainActivity to read the response. RESULT_OK is a constant of Activity so we don’t need to declare it. Then we pass the Intent that we created with the data as well. The final call will finish this current Activity and transfer control back to the Activity which started DetailActivity, which is MainActivity. Let’s take a look at what this Activity is going to look like.

Intents – 2

Now let’s go back to MainActivity and display the response. Let’s override onActivityResult(...)  method.

In this code, we first check if the resultCode turned out to be RESULT_OK, which it did. Then we make sure that the requestCode corresponds to the code we sent initially. Finally, we create a Toast message and extract the string from the Intent using the key. This is all there is to do! Let’s run our app!

Intents – 3

You can see that when we tap on a list item, we transition to DetailActivity that has the name of the country in the center of the screen. When we press on the backwards-navigation arrow, we have a Toast message that says “All is well!”

Conclusion

In this post, we covered how we can use Intents to start other Activities and pass data to them. We also learned how to pass data back to the initial Activity as well. As a bonus, we also went over how to reuse layouts through the include tag and a bit about the mysterious AndroidManifest.xml file. Intents are very important since we can use so that we don’t have to create an Activity for everything! For example, if we want an image, we ask the system, via an Intent, to take the user to the Camera app. Then we can get the image back in onActivityResult(...) ! It’s really that simple! To summarize, Intents are powerful objects that will make our Android coding go a lot smoother!

Published by

Mohit Deshpande

Mohit Deshpande is a professional mobile application developer, contractor, and instructor. He started programming at the age of eleven. During the great mobile revolution, he shifted focus to developing mobile apps with his first Android app running on a Samsung Galaxy S1 running Android 2.1 Eclair. Since then, he has been involved in industry and research. He is a computer science and engineering student at The Ohio State University and works for the Department of Computer Science and Engineering as a researcher. During the university hackathon, he came in second place with an Android app that links a task with a location using a geofence. In what little spare time he has, he plays jazz and rock guitar and performs in the Ohio State Athletic Band on trumpet at various sporting events.

Share this article

  • pranav moyal

    Nice Article….