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!

A Simple App! (Part 1)

Posted on Updated on

Hi everyone!

Having discussed most of the basic concepts required to start the development of Android apps, let’s not wait any more! Let’s go straight to the development!

Today, we will start building the simplest version of the Hello World app (other than the one which is automatically generated! Remember? Refer to Let’s Code!) , in which we will focusing on the use of buttons and toasts(?? Don’t worry! I will discuss!)  in Android applications. In the coming few posts, I will be building upon this tutorial to discuss the various concepts finally leading to the development of the app.

So, Let’s start! Open the Hello World Project that we created in the post titled Let’s Begin!.

Go to main.xml in the layout folder, drag a button from Form Widgets and place it onto the WYSIWYG screen. Go to the code! Is there any difference from the code discussed earlier?

Yes! We have a new tag named Button with various attributes! Let’s focus on each of them.  Clearly, android:layout_width and layout_height are used to define the width and the height of the button respectively. By default, they are set to wrap_content. I hope you are familiar with this term. If not, please refer to the post titled A look at the code!.

Change the android:layout_width attribute of the Button tag to fill_parent in order to make the button stretched to the entire width of the screen, and leave the android:layout_height as it is.  Save main.xml. Your screen in the WYSISYG editor should look as follows:

Refer to the code again. There are two more attributes for the tag Button. The android:text attribute sets the text which is displayed on the button. By default, it is set to Button and that’s why, the default text on the Button widget is Button.

You may also find a warning on this line.  Can you guess why is it so? Basically, in the code that is generated automatically, android:text attribute has been set to the string Button whereas as per the correct syntax, one must declare a string variable (for example, button) whose value is Button and then, reference it by using @string/button in the value of this attribute. To fix it, simply click on the attribute, right click and choose Quick Fix. You will be provided with various options. Simply, select Extract String which will display a dialog box, in which set the R.string value to button and String to Button. Click OK and save the file. The text Button will replaced to @string/button and the warning will be gone.

We will look at the android:id attribute later. For now, simply run the project. What do you see?

You will find that there will be a button on the screen but, when you click it, nothing happens! Why?

In the next post, we will discuss the android:id attribute and it’s use in implementing the functioning of a button.

Till then, BYE!

 

Let’s Code!

Posted on Updated on

Hi all!

So, I am back again. This time, we will delve into the coding arena and try to understand the code that is automatically generated when you create a new project (Remember! when we had run the project in the post titled Let’s Begin! , an app was launched in the emulator in spite of the fact that we had not written any code ourselves).

How did that happen? We have already seen that the layout which is automatically created when we make a new project is exactly same to the screen of that app. What about the rest of the its functioning? Who tells Android to set the screen to that particular layout? Let’s see!

If you open the project, click on the package name (in our case, it was com.hello.world) and open the source file (which is HelloWorldActivity.java in our HelloWorld project discussed in previous posts), you will find a few lines of code. The code which does the task mentioned above. But, the question is How?

The first line of code is simply to tell the package name to which this class belongs to(Class? For now, it is sufficient to understand that it is the most basic component of a JAVA code, which encapsulates other functions and variables . We will look at them in a greater depth in the coming posts). It’s the same as selected while making the project. The second line of code simply imports the android classes that are already present in the Android framework and provide us the functions required in the code.

Now, you can see we have declared a class with an access modifier called public which poses no restriction on the access (For those who are unfamiliar with it, we will come to that later). The name of the class is same as the name of the java file. Now, the code says that this class extends an Activity. So, what is an Activity? An activity is the top level component ( a pre-built class) which controls what you see on the screen. It may either cover the entire screen or a part of it, but only one activity runs at a time in Android. So, even if the activity covers just a part of the screen, the remaining part will be inactive till the time that activity is running.

So, the third line of code basically declares a class with no access restrictions, which extends an Activity (because of which we call this class an Activity as well!) so that it can interact with the screen, which means that this class can use all the functions and variables provided by the Activity class.

The rest of the code simply defines a function which is automatically called when this activity is first created. We don’t have to remember the syntax as this function is automatically generated. There are two things happening in this function. We don’t need to discuss the first one.

What about the line setContentView (R.layout.main)? Can you guess what this line of code does?

In the next post, we will discuss this line of code and also, dive deeper into the coding world of Android App Development.

Till then, BYE!

Final say on layout!

Posted on Updated on

Hello all!

So, it’s time to culminate our initial discussion on layouts. Till now, we have looked at the WYSIWYG editor, the code for the layout and a visual editor for playing with strings. Now, we shall come to the query raised in the last post, i.e., the value taken by the android:string attribute of the TextView which is described in the line:

android:text=”@string/niktechs” 

For those who have been following this blog, it must be really easy now. But, still I should give the details for the sake of completeness.

Clearly, @string is a way to tell the compiler that the variable which will follow after a ‘/’ represents a string. This is necessary to distinguish the different types of variables. Yes! There are other kinds of variables which represent color, dimension, array, etc. Right now, I am not going to discuss how to use those variables. But, if you are one of those who really like to stay ahead, open the strings.xml and click on add. You will see the following dialog box.

Now, it’s on you to explore!

Also, the name that follows the ‘/’ is the name of the variable whose value is to be given to the android:text and thus, is to be displayed on the screen. Here, since the name is niktechs, the text that is displayed on the screen will be same as the value of the variable niktechs which is Developing Android Applications with Nikhil Gupta.

Now, I think I have laid the foundation of discussing the other way of changing the text on the screen. Remember, in the post titled Laying out the screen!, we saw how to use WYSIWYG to change the text on the screen. For a quick flashback, we used the edit text option and created a new R.string whose value was the text that we wanted to display.

The other way results from our discussion in the previous post. There, I created a new variable of type string named Blog. Now, instead of using the WYSIWYG editor, we can simply change niktechs (in the code describing android:text attribute) to Blog and save the file.

Now, look at the GUI (click on main.xml and then, choose Graphical Layout tab). What do you see? Yes, the text has been changed to Android Development which is the value of the variable Blog. Why does this happen? I hope that it’s now trivial for all. Since Blog is just another string type variable like niktechs (discussed in the previous post), replacing the two will result in replacing the values of the android:text attribute and hence, the text on the screen.

So, we have looked at the basic layout features and understood each and every concept related to it. But there are various attributes that can be used in the code for layout which can greatly vary the screen. It’s up to you to explore them. I may discuss a few of them, but only in the later posts. If you want to explore, go to a tag, type android: and press Ctrl+Space. You will see the entire options that are possible.

In the next few post, we will finally go into the JAVA coding. So, a lot more interesting stuff coming soon!

Till next time, BYE!