You are on page 1of 15

Half Dozen Hello Worlds Part 1 – Your First Android Project

Hello World is a traditional first program because it shows the very simple task of letting the user
know you are there (or letting them know that you know that they are there). It’s simple I/O to send
a simple message. I am going to give a very brief tour of some of the ways you can communicate
with a user in Android in this post. Half Dozen Hello Worlds will highlight some simple I/O and
get you started writing your first Android programs. First let’s go ahead and open Eclipse, where
you have already setup Android, and create a new Android Project. Go to File -> New -> Project.
Select Android Project and click next.

Fill out the information on the next screen for your project.
You can put whatever you like for the project name, and application name. Note that I selected
Android SDK 1.1. It is a good idea to select the oldest SDK which has all of the features your
program needs, to increase compatibility across devices. You can think of Create Activity as being
similar to create Main Method. The name of the Activity you place here is the class that will be
called when Android tries to run your code. Once you click Finish you should see the Project.
If you expand the project, then expand the src folder, and
then the package you will see a Java file. This file will be named whatever you called your Activity
(so mine is Hello.java). For simplicity I am going to assume you used the same settings I did when
creating your project. If you did not just substitute your Activity name for mine. Double click on
Hello.java and look at the code that Eclipse has already provided you.
package com.learnandroid.hellowworld;

import android.app.Activity;
import android.os.Bundle;

public class Hello extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

Just to give a quick overview. The package declaration just places this class in the package we
specified when we created the project. The two import statements just import the minimum
Android libraries needed for an Activity. Since Eclipse created this as an Activity it is going to
inherit from the Activity class, and we are overriding onCreate, which is called when an Activity is
created. We call onCreate of the superclass. Finally, we are at the one line of code we really care
about right now.
setContentView() tells android what to display to the user. We are going to change this from the
default so that our code looks like this:
package com.learnandroid.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Hello extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView helloText = new TextView(this);
helloText.setText("Hello World");
setContentView(helloText);
}
}

Let’s briefly look at exactly what we did before moving on. TextView is an android widget that
displays text. You can think of it as a label, something the user can read but cannot edit. We
instantiated a new TextView. Then we called the setText method to set the text of it to “Hello
World”.
Next we used setContentView to tell Android that our TextView was what we wanted to display in
the main part of our application.
Once your code looks like mine, go to the Run Menu and select Run… In the Run As Popup select
Android Application. Your Android Emulator should launch. The Emulator will normally start on
a lock screen, but as soon as you unlock the device you should see your application launch.

Congratulations! You have built the first Hello World. This is not the preferred method for
creating an android application, however, because the contents of the View (what the user sees) is
being generated directly from the code. Android prefers that this be separated out of the code and
placed into an XML file. We’ll look at how to do this next in Part 2 of this series.
Half Dozen Hello Worlds Part 2 – Using Layout XML
This is part 2 of a multipart series that looks at some basic Android I/O using some simple Hello
World programs. If you haven’t already read it you should probably start with Part 1. For this part
we are going to create a new project with these settings.

The
default Hello2.java will look very similar to the default Hello.java from Part 1.
package com.learnandroid.hellowworld;
import android.app.Activity;
import android.os.Bundle;

public class Hello2 extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

This time, however, we are going to find out more about the line setContentView(R.layout.main);
In the first example we used setContentView to render our TextView to the screen. By default,
however, Android is designed to use XML files to setup your UI. In addition to the src folder,
which holds the source code intended to be edited by the developer, there is a gen folder and a res
folder. The gen folder holds automatically generated code. If you open this folder and expand the
namespace you should see R.java. We’ll come back to R.java in a moment. Before we open that
file, lets also expand the contents of the res folder. The res folder holds resources for your android
app. By default you should see three folders in here, drawable (which holds an android icon), layout
(which contains main.xml), and values (which contains strings.xml). If you open main.xml and
click on the main.xml tab you should see the XML that provides your activity its layout.

We
aren’t going to go into too much detail in this post on the UI XML. I will highlight, however, that
the main node is LinearLayout which is a Layout Container that simply lines its children up in order
one after another. android:orientation indicates whether they are lined up vertically or horizontally.
The one child node we have in LinearLayout in a TextView. This is the same control we used in
Part 1, but instead of instantiating it in our code we are using the UI XML to tell Android to provide
us with one. The other thing I want you to notice is the line android:text=”@string/hello”. This is
going to set the value of our TextView. If you go back to the res folder, open values, open
strings.xml and click on the strings.xml tab you can see exactly what value we are putting into our
TextView. In strings.xml there is a line
<string name=”hello”>Hello World, Hello2!</string>
so android:text=”@string/hello” will get this value and place it in the TextView that is displayed to
the user. Let’s go ahead and change the value to our simple “Hello World” now.
<string name=”hello”>Hello World</string>
Go ahead and save your change and close both strings.xml and main.xml. At this point you are
probably wondering how Android gets the information from the XML files and uses them in your
program. Go back to the gen folder and open R.java and we’ll see the answer.

When R.Java is generated it


creates a class for each resource type (drawable, layout, and string) and variables in each class
providing access to your resources. so R.layout.main actually maps to your main.xml file via this R
Class and the layout inner class. If you don’t exactly understand what is going on here don’t worry.
Just remember that R will let you access items in your res folder so the line.
setContentView(R.layout.main);
tells android to use the layout in your main.xml file in res/layout. Since we edited the value in
string.xml we should be able to run this program and see our “Hello World” displayed. Before we
move on to part three, let’s modify this program a little bit to show how to access a View element
(such as our TextView) in our code.

Half Dozen Hello Worlds Part 2 – Using Layout XML


In order to make our TextView accessible in our code we’re going to start by opening main.xml
in /res/layout and editing it like so:
We’ve removed the line
android:text=”@string/hello”
and replaced it with the line
android:id=”@+id/label”
The @+id tells Android that we are giving the TextView an ID inside of our Application
Namespace. This will allow us to access it in our code. Let’s open up Hello2.java in our src folder.
package com.learnandroid.hellowworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Hello2 extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView label = (TextView) findViewById(R.id.label);
label.setText("Hello World");

}
}

We’ve added two lines of code. The first:


TextView label = (TextView) findViewById(R.id.label);

uses the findViewById method to get the View, which we cast to a TextView. Notice how our
automatically generated R class automatically provides us with the id we defined in main.xml. The
next line:
label.setText("Hello World");

Simply sets the text to Hello World. If you run this application now you should see (once again)
Hello World on your screen. That wraps up part 2. Make sure to check out Part 3 of the series
where we explore two kinds of pop-up messages available in Android.
Half Dozen Hello Worlds Part 3 – Using Popup Notifications
This is part 3 of a multi-part series that looks at some basic Android I/O using simple Hello World
programs. At this point I’ll assume you know how to make a new Android Project in Eclipse as that
was covered in Part 1. In this part we are going to look at two types of pop-up messages that allow
you to communicate with the user outside of the normal program flow.

Toasts
Imagine you are at a large dinner party. You want to make a toast to your host. You raise your
glass a call out a toast. Half the people at the party don’t notice (none of the kids at the kids table
notice at all), but you aren’t worried about that as you clink glasses with the dozen people who did
notice. The first pop-up we are going to look at is Android’s Toast, which does exactly this. It
allows you to present a message to the user without any confirmation that they noticed the
message. Build a new project using Android SDK 1.1 and update your Activity Java to look like
this.
package com.learnandroid.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;

public class Hello3 extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Toast helloToast = Toast.makeText(this, "Hello World",


Toast.LENGTH_LONG);
helloToast.setGravity(Gravity.CENTER, 0, 0);
helloToast.show();
}
}

The first line of code we added to the default code generated by the project was this.
Toast helloToast = Toast.makeText(this, “Hello World”, Toast.LENGTH_LONG);
This line of code calls the Static method makeText of the Toast class. The makeText method
returns a Toast object that will display the message you provide, in our case “Hello World”, for the
duration you specify. The two available durations are Toast.LENGTH_LONG and
Toast.LENGTH_SHORT. Once we have our Toast object we can just call the show method to
display it on the screen. Before displaying our toast, however, I thought I would center it on the
screen. The setGravity method lets you tell Android where the toast should be displayed by using
one of the Gravity constants, and then specifying an x offset and y offset. Since I wanted it in the
very center of the screen I used Gravity.Center and specified offsets of 0.
helloToast.setGravity(Gravity.CENTER, 0, 0);
You can see a list of available Gravity constants here. When you run this code you should see a
small pop-up with the message “Hello World” appear, and then disappear automatically without any
user interaction. On the next page we’ll look at a pop-up that requires user interaction.
Alerts
When I was a kid I used to love The Great Muppet Caper. I vividly remember a scene where
Gonzo shouts, “Stop the Presses!” The editor asks him what happened and he says, “I just always
wanted to say that.” If you want a pop-up that makes sure it gets attention (whether something
important happened or not) then an Alert might be just what you need. Let’s update our Java
Activity to look like this:
package com.learnandroid.helloworld;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

public class Hello3 extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

AlertDialog helloAlert = new AlertDialog.Builder(this).create();


helloAlert.setTitle("Half Dozen Hello Worlds Demo");
helloAlert.setMessage("Hello World");
helloAlert.setButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.show();
}
}

The lines we’ve added are:


AlertDialog helloAlert = new AlertDialog.Builder(this).create();
helloAlert.setTitle("Half Dozen Hello Worlds Demo");
helloAlert.setMessage("Hello World");
helloAlert.setButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.show();

The AlertDialog Class makes use of the Builder Class AlertDialogBuilder. So in the first line when
we call:
AlertDialog helloAlert = new AlertDialog.Builder(this).create();
We are using the Builder to return an AlertDialog object to us that is already partially setup for our
use. The next two lines use setTitle and setMessage to set the text displayed to the user in the
dialog’s title section and body respectively. Finally, we need to have a way for the user to actually
interact with our alert. At minimum we should have a close button so the user can make the alert go
away. We use setButton, passing it the text that should be displayed on the button, and an event that
allows us to perform actions when the button is clicked. By default, the dialog will be closed on a
click event so we don’t need to put any code into our event. Finally we call the show method, like
we did with toast, to display our Hello World pop-up.
While that technically finishes both of our Hello World pop-up programs I want to take a moment
to examine the buttons on the AlertDialog
AlertDialog Buttons
In SDK 1.1 there were three methods we used to make buttons in our AlertDialog: setButton,
setButton2, and setButton3. In our example here we are only using setButton. That will give us a
single button that is centered horizontally in the AlertDialog. If we also called setButton2 we
would have two buttons side by side with our first button on the left and our second button on the
right. If we include all three buttons like this:
AlertDialog helloAlert = new AlertDialog.Builder(this).create();
helloAlert.setTitle("Half Dozen Hello Worlds Demo");
helloAlert.setMessage("Hello World");
helloAlert.setButton("Button", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.setButton2("Button2", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.setButton3("Button3", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.show();

We would see our first button on the far left, the second on the far right, and the third in the middle
like so.
If the numbering seems a little arbitrary to you then you may not be alone since these methods were
deprecated. Let’s build this code using a more recent Android SDK. Right click on your project,
and click on Properties. Click on Android, and click on the check mark next to either Android 1.5,
Android 1.6, or Android 2.0. Then click Apply, and then OK.
Go to your code and replace this code block
helloAlert.setButton("Button", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.setButton2("Button2", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.setButton3("Button3", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});

With this:
helloAlert.setButton(AlertDialog.BUTTON_POSITIVE, "Button", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.setButton(AlertDialog.BUTTON_NEGATIVE,"Button2", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});
helloAlert.setButton(AlertDialog.BUTTON_NEUTRAL ,"Button3", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {}
});

You can see that the new method for adding buttons is to call one single method (setButton) and
pass a constant telling Android how to render it.
This is the end of our introduction to popup notifications, but come back for Part 4 where we will
use Text to Speech to make your Android Device actually say “Hello World.”

Half Dozen Hello Worlds Part 4 – Android Text to Speech


This is part 4 of a multi-part series that looks at some basic Android I/O using simple Hello World
programs. At this point I’ll assume you know how to make a new Android Project in Eclipse as that
was covered in Part 1.
In this part we are going to look at using Android’s Text to Speech capabilities to get our Android
device (or emulator) to actually say “Hello World” to the user. Text to Speech was introduced in
Android 1.6, so when you create your new Android project make sure your minimum required SDK
is set to Android 1.6 (or API level 4). Here is the code we are going to use to make our Android
device speak to us.
package com.learnandroid.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

public class Hello4 extends Activity implements OnInitListener


{

private TextToSpeech tts;


static final int TTS_CHECK_CODE = 0;

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

tts = new TextToSpeech(this, this);


}

@Override
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS)
{
tts.speak("Hello World", TextToSpeech.QUEUE_FLUSH,
null);
}
}
}

The first thing you should notice here is the line:


public class Hello4 extends Activity implements OnInitListener

This is different from what we have seen before because it has the extra part at the end “implements
OnInitListener”. If you are familiar with Java you know that implements the OnInitListener
interface. This will allow our activity to respond to the event triggered when the TextToSpeech
engine finishes initializing. We will use the onInit method for this purpose later in our code.
Inside the class I’ve defined a class variable:
private TextToSpeech tts;

so it will be available to both methods in our activity. Then in the onCreate method I initialize the
variable using the TextToSpeech class.
tts = new TextToSpeech(this, this);

If you get an error on this line make sure you have the import android.speech.tts.TextToSpeech;
statement at the top. in Eclipse you can use Ctrl + Shift + O to automatically update your import
statements.
The constructor for the TextToSpeech class takes two parameters. The first specifies the the
context in which we’re running, and the second is the OnInitListener that should be called. Since
our Hello4 class inherits from Activity we can use it for the context, and since it implements
OnInitListener we can use it for the OnInitListener. Thus I simply provided the keyword “this” for
both parameters.
Since we specified our class as the onInitListener to use, the class method onInit will automatically
be called when the TextToSpeech class is initialized.
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS)
{
tts.speak("Hello World", TextToSpeech.QUEUE_FLUSH,
null);
}
}

This method is passed a integer indicating the status after initialization. We will compare this status
code to the constant provided by the TextToSpeech class to indicate successful initialization
(TextToSpeech.SUCCESS). If Initialization was successful we will call the speak method to
actually have your android device speak “Hello World”.
tts.speak("Hello World", TextToSpeech.QUEUE_FLUSH, null);

This method takes three parameters. The first is the text that should be spoken. The second is the
mode to use for speech. The mode used for speech can allow you to either speak the text
immediately (using QUEUE_FLUSH as we did here) or queue up multiple strings to be read. Since
this is intended to be a very simple example we won’t cover this functionality here. The final
parameter allows you to pass a list of additional parameters. This is also outside the scope of this
example.
This is the end of our tutorial on Text To Speech. Thanks for reading and be sure to check back;
there is one more Hello World example forthcoming.

You might also like