Transfer of data using Intents (Part 2)

Posted on Updated on

Hi everyone!

In spite of trying hard, I couldn’t prevent the delay. I am again sorry for that. Let’s move on. In the last post, I introduced the concept of transfer of data between activities. I also described the code for declaring an Intent which could help us in accomplishing the task.

Now, it’s time to look at the code of SecondActivity.java, the second activity which will help us in adding new tasks to the list. As mentioned earlier, this activity will have an EditText to allow the user to input the task name and a Button, which when clicked, will take the user back to HelloWorldActivity.java and add the task to the List. The code for the click listener for this button looks as follows:

  1. String taskName = taskEdit.getText().toString();
  2. Intent intent = this.getIntent();
  3. intent.putExtra(“task”, taskName);
  4. setResult(RESULT_OK, intent);
  5. finish();

Here, taskEdit is an object of class EditText. The first line extracts the data input to the taskEdit, converts it into string and stores it in a variable. Second line is used to grab access to the intent which called this activity. The third line is the one which actually does the job of putting the data onto the intent. intent.putExtra function used in this line basically adds the information contained in the second parameter to the intent and the first parameter provides a way to access it. We will see the use of the first parameter in a greater detail later, when we will try to access this information in HelloWorldActivity.java. I hope that the fourth and fifth lines will be pretty easy to understand. If not, please refer to the last three posts on Intents.

The above code ensures that the clicking of the button takes us back to the initial activity with an intent which contains the name of the new task that is to be added to the list.

Clearly, the callback function described in Part 1 of this post will be used to access the information carried by the intent since this function will be automatically called when the control is given back to this activity via an intent. Straight away, let’s look at the code!

String extraData=data.getStringExtra(“task”);
taskText.append(extraData+”\n”);

I think it is self-explanatory. We are extracting the information from the variable data using the value of the first parameter of the function in Line 4 above, and saving it in a variable called extraData. The second line just appends this value to the list (referred by taskText).

In this way, we received the name of the task from a different activity and display it in our main activity. This provides a clean and user-friendly interface which is the basis of a useful app.

But here, we have not taken care of the situation when the user calls the intent to SecondActivity.java but wants to cancel it later. This is not perfect programming, though it can be dealt very easily. How?

In the next post, we will finish our discussion on intent and move on to explore some new concepts in Android App Development.

Till then, BYE!

Transfer of data using Intents (Part 1)

Posted on Updated on

Hi all!

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

startActivityForResult(intent, 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);
          if(resultCode==RESULT_OK)
          {
                      //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!

Intents-An Example(Part 2)

Posted on Updated on

Hi all!

Finally, I got some time to continue with the example. I am really very sorry for the long delay. From now on, I will be posting every two to three days. So, keep looking!

For a flashback,  we discussed the use of intents in achieving communication among activities. We also saw the basic code of the two activities which will communicate with each other in the last post. Without wasting more time, let’s discuss the final codes for both of these activities.

Remember! I told you that we will be playing with the onClickListeners of both the buttons in the respective activities to accomplish the task.

Let’s start with the code for SecondActivity.java. Remove the code for showing the toast and replace it with a function called finish(). Yes! That’s it.

On clicking the button on the second activity, we just need to finish this activity and move back to HelloWorldActivity.java. Since, we will be calling this activity only from HelloWorldActivity.java (How to call from others? We’ll see!), finishing this activity will automatically take us where we want. Hence, the code for SecondActivity.java is over.

How about HelloWorldActivity.java? It’s the place where we will be actually calling the intent.

So, replace the code for the toast in the onClickListener with the following lines of code:

Intent intent = new Intent(HelloWorldActivity.this, SecondActivity.class);
startActivity(intent);

I hope that you are able to understand it clearly. We are basically making an object of class Intent passing to it two parameters. The first parameter is a reference to the current activity. this is a keyword which always refers to the current object. Hence, HelloWorldActivity.this simply specifies the activity from which the intent is being called. The second parameter is the one which specifies the activity to which we want to move. Remember, we specify it as .class. Hence, we have specified the second parameter as SecondActivity.class. But, the first line declares an Intent object called intent. To actually accomplish the task,  we need to call a function called startActivity with the parameter as the Intent object, which transfers the control to the activity specified while declaring the Intent object.

So, just run the above application and check out what it does! You will see that you will be able to go back and forth every time you click the button on the screen.

But, there is no practical use of this communication. Intents become more meaningful when we need to transfer some data from one activity to another.

In the next post, we will be looking at an application which involves some useful transfer of data.

Till then, BYE!

 

Intents – An Example (Part 1)

Posted on Updated on

Hi everyone!

Sorry for the delay in the post this time! Let’s go ahead!

In the last post, I gave an overview of something called Intents in Android. If you have not gone through it, please refer to Communication between Activities using Intents! first and then, come back here!

This time, I am going to discuss the simplest app which can demonstrate the use of Intents. Even though, the app in itself is of no use but, concepts discussed during its development will help us in our future endeavors. I will be building on our previous HelloWorld App which (till now) simply shows a Toast when we touch a  button on the screen.

First of all, we will be needing two activities in our project which will be communicating with one another. So, simply go to the project folder in the HelloWorldApp that we have been developing upon, right click, select New and the, click on Class. Fill the fields as per the following figure and select Finish.

A new activity called SecondActivity.java has been created. But, you will see that there is no onCreate function. Just copy the code from below. It will be exactly the same as the one automatically generated when you create a new project and hence, you don’t need to remember it.

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
 }

Note the change in the value of the parameter of setContentView. Yes, it refer to a new layout file called second.xml. Simply make a new file called second.xml in the layout folder and copy the contents from main.xml to this file as we want the similar layout for this activity too. To create the new xml file, simply right click on the layout folder and select New->File. Name the file as second.xml and select Finish. Remember to give a different ID to the button of second.xml to avoid conflicts. Just change the value of android:id attribute of Button tag to something that was not used for main.xml. Let me change it to button2. Also, change the text of this button so that we could distinguish between the two activites.

Now, we need to play with the onClick Listeners of the two buttons (present in the two activities) to start the communication. In this app, we simply want to switch between the activites when the button is pressed. When we click the button on HelloWorldActivity.java (Default Activity of our app), we want to switch to SecondActivity.java and when we click the button on SecondActivity.java, we want to return to HelloWorldActivity.java.

Try to search and write the code for the same yourself based on our discussion in the previous post. In the next post, I will discuss it and some more concepts in the Android app development.

Till then, BYE!

Communicating between activities using Intents!

Posted on Updated on

So, we have completed the development of our first app and it’s time to move on! This time, we will ponder upon the question, “How to communicate between activities?”, i.e., Is it possible to switch from one activity to another in an app and if so, how? This post will try to answer most of these questions?

Let’s start from the very basic question! Why do we need to switch between activities? In an app, we need to have multiple activities which perform various tasks. As an example, a Message application has at least an Activity for showing the entire list of threads and an activity for creating new messages. Hence, we need to switch between these activities over and over again in order to make a user-friendly Message application. Similar situation arises in most of the apps since most of them consist of more than one activity.

So, we can see that we need to switch between activities, and most of the apps consist of various activities which can switch between one another.  Now, we need to see how it is possible. Clearly, the title of the post suggest that there is something called Intents in an Android App which can help us in this regard.

Intent is the part of the Android framework which facilitates communication between activities. An intent can be treated as a function which can be called in an Activity with the parameters which (in broad sense) give the location of the activity to which we need to switch over.

One can use intents to not only switch between activities, but also to share some data from one activity to another. We will talk about it in detail later.

Once an intent is called, the control switches over to the other activity. The other activity after completing its job can simply call a function finish() in order to finish the activity and pass the control to the earlier activity.

When the control is sent back to the earlier activity, a specific function (called a callback function) is executed which can be used to process the data sent by the other activity (if any!).

So, we have discussed the complete flow of control with the use of Intents! In the next post, we will start the development of the second app based on intents where we will look at the exact code.

Till then, BYE!

 

A Simple App! (Part 3)

Posted on Updated on

Hi everyone!

Let’s continue from where we left! So, I used Toasts in the previous post. Were you able to figure out what this does? I hope so!

It is basically used to show notifications on the screen. If you are an Android User, you must have encountered them while using Messages or Contacts application. We had also seen the code for the same. Let’s revisit it!

Toast.makeText(getApplicationContext(), “Hello World!”,Toast.LENGTH_SHORT).show();

Simply, Toast.makeText(params).show() is the function which is used to display a Toast on the screen. It’s parameters are used to define it’s various properties.

The first parameter is used to pass the context to the function. Mostly, we will be using getApplicationContext() as the value of this parameter since this provides the context required to display the Toast on the screen in our app (We will be discussing it in detail later).

The second parameter defines the text to be displayed in the notification. Here, Hello World! will appear on the screen. A string type variable can also be used here!

The third parameter simply defines the time for which the notification will be displayed. It can have two values:

  1. Toast.LENGTH_SHORT: Used to display the notification for a short period of time.
  2. Toast.LENGTH_LONG: Used to display the notification for a long period of time.
Now, I think we have understood how to use Toasts in our application.

So, we have completed the development of our first app! Let’s look at all the steps again:

  • We had changed the value of the default TextView to Developing Android Applications with Nikhil Gupta in the post titled Laying Out the Screen!
  • We added a Button to the layout in the post titled A Simple App! (Part 1).
  • We discussed the use of ID and its usage as an attribute in the layout and as a reference in the JAVA code in the post titled A Simple App! (Part 2) .
  • We finally discussed the use of Toasts in this post.

We will start with the development of a new and interesting app in the next post!

Till then,  BYE!

A Simple App! (Part 2)

Posted on Updated on

So, it’s time to continue with the development of the app (which we started developing in the previous post). First of all, let’s look at the android:id attribute of the tag Button.

By now, we know that id is used to provide a unique value to a component which can be used to access it later anywhere in the project. As an attribute, its value starts with @id. In our code, we can see that @+id has been used. Why is it so? Any guesses!

Actually, when a particular ID is used first time for a component, we need to use @+id to tell the compiler to assign the given value as the ID of the component.

Thus, the following line of code

android:id=”@+id/button1″

basically assigns the id button1 to the Button on the screen. Later, we can use @id/button1 to refer this component while defining a value of an attribute. What does that mean? Suppose, while defining the layout, I want to refer to this button in some attribute of some tag. In that case, I will be using @id/button1. But, We need to use something else in order to reference this button in the JAVA code. Let’s see!

We have understood the layout of the app. Now, let’s open HelloWorldActivity.java. So, we need to refer to that button. How will we do this? For simplicity, let us call a function setUpViews() in the onCreate funtion. Since, this function has not been created till now, Eclipse will show an error. To rectify, simply hover on it and Select “Create method”. It will automatically create this function as a member of the Activity.

In the function, write this line of code:

NotifButton = (Button) findViewById(R.id.button1);

Can you make out what this does? R.id.button is used to reference the button in the code. How? R.java is the file that acts as a link between the code and various components and resources. I think id.button1 is self-explanatory. (For curious readers, open the R.java file in gen folder and explore!).

findViewById is a function used to provide a handle to the component using which various functions provided by Android SDK related to a component can be accessed. Difficult? Don’t worry! Treat it simply as an identifier which can be used to interact with the component. You can also see that the output has been type-casted to type Button. This is required as this function is used for various components and returns a generic handle which must be type-casted according to the component.

After this long story, the conclusion is that NotifButton is a handle to the component Button (whose id is button1). Also, when you write this line, an error is shown since NotifButton has not been declared. Simply hover over it and select “create field NotifButton”. Why not others? Try to find out.

Now, it’s time to use a function which is executed every time button is clicked. This is done using the following syntax:

NotifButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

}
});

This is just a syntax used to access this kind of function. Anything written in the onClick block gets exceuted when the button is clicked. For now, write the following line of code in the onClick function.

Toast.makeText(getApplicationContext(), “Hello World!”,Toast.LENGTH_SHORT).show();

Save the file and run the project. What happens?

In the next post, we will look at the above line of code and discuss some other coding aspects in Android App Development.

Till then, BYE!