Last time, we had looked at the most basic communication which can be achieved among activities. It allowed us to switch between activities back and forth, which is an important concept used in almost all the android apps these days.
Moving on, it’s time to look at the data transfer using Intents. Consider the case of a simple Task application, in which a To-do list is shown in one activity while another activity performs the task of adding new items to the list. So, what’s happening here?
Basically, we need to create a new task in the second Activity and somehow transfer it to the first activity so that it could add it in the existing list. Note that we are not using any database. If we do so which is done most of the times, this app will be useless in itself. But, I am still discussing this app because I feel that it’s the best in order to understand the concept of transfer of data which you may need in various other apps.
In this post, I will not go through the layout or the entire code of the app. I may go through it later. But, I hope that you will be able to do so after going through the previous posts. As a hint, we will be using a TextView (to display the list) and a Button while making the first activity, while the second Activity will have an EditText and a Button.
Assuming that we have an EditText in the second Activity and when the user presses enter, the string in the EditText is captured in a string variable called NewTask, we need to simply tranfer the contents of NewTask to the first activity.
To achieve this, we need to call the intent when the button in pressed in the first activity in such a way that the Android platform knows that some data will be coming back to this activity. Continuing with the app from the previous post by replacing the startActivity(intent); by
1 as a parameter acts as a unique code used to distinguish data received by this intent from the data received by other intents if more intents are used. Using the above functin, we have been able to call the intent, but we have not yet accessed the data which comes back with this intent.
To achieve this, we need to use a callback function which will called automatically when the intent returns. Let’s look at the code for this function:
public void onActivityResult(int requestCode,int resultCode,Intent data)
super.onActivityResult(requestCode, resultCode, data);
//Code to extract the required information from the variable data
In our case, requestCode is 1. resultCode is a variable which is set to value RESULT_OK if the intent was successfully handled. data is the variable which contains the data received from the other activity.
In the next post, we will look at the code to extract the information as well as the code for the second Activity which puts the information in the intent.
Till then, BYE!