Using Android Intents Tutorial
The Activity You Know
While we already discussed opening a specific activity in a previous article we also need to look at how to interact with an activity we open. So previously, we used this line of code when opening our activity.
This is a call to the startActivity method which expects an Intent to be passed in as a parameter. This method opens a new Activity and then forgets about it completely. That fine if this is the behavior you want, but what if you want to know what the user did with the new activity? To accomplish this, we are going to use startActivityForResult. Let’s go ahead and implement our onListItemClick method to handle when the user clicks on a list item.
The line of code we are interested in here is this one:
We are starting a new activity, but this time we are telling Android that we expect to get a result back. As we did with startActivity in this article we are passing in an Intent with the class of our Activity. We also pass in a request code. This can be any integer and can be used to determine which request is being examined. For now I’m just going to use 1701 because I’m a Sci-Fi fan. Don’t worry about this for now, just put whatever positive integer you want here (Android will only return codes >= 0).
So far, this isn’t any harder than just calling an activity. Okay, let’s go ahead and create the new class we are going to open like so:
The only thing that should be new to you here is the contents of our onClick method.
First we create a new Intent to use for passing data back in our response. The intent provides “Extras” as a way of passing extra information we need. We put an extra in the intent, in our case whatever string the user has provided. Then we call setResult in order to tell Android what result the calling activity should be sent. Finally we call finish, which destroys our current activity and takes us back to the previous activity. One thing to note is that each extra is given a name. I just used “Name” as the name of my extra since that’s what it represents, but it can be any string. We will use the name to retrieve the extra data.
When the activity that was called using startActivityForResult finishes it sends its result back to the calling activity by calling the onActivityResult method. So let’s override that method and do something with our result.
Just to keep things simple, I am just going to use a popup (covered in this article) to display the value that was in the EditText. The Intent variable named data is the same intent we placed into our result. I retrieve the name we put into an extra by calling getStringExtra here. Our final result should look like this.
No comments:
Post a Comment