Monday, February 28, 2011

First Android app - Hello World!

In the previous blog, we set up the environment for creating Android projects
using Eclipse. We also saw how to set up a virtual device. After we create the
AVD(Android Virtual Device), we are ready to create our first program.
As is the tradition, the first program in any language is a small Hello World
program.

So let’s get started.
  1. Start Eclipse.
  2. Select File > New > Project.
  3. In the New Project dialog, select Android > Android
    Project.
  4. Click Next.



5. Fill in the details as shown below and click Finish.


 6. Our android project is now ready. It should be visible in the “Package
Explorer” on the left hand side.



Let’s see the folders of the project:
a.     src
This folder contains the Java source files that you will be creating. In the
screenshot you can see the ‘activity’ files that were created for the sample
project i.e. HelloAndroid. The files inside this  folder will be organized
according to the package structure. This is similar to the /src folder which is
present in any normal Java project.
b.     gen
This is also a source folder, but it contains Java source files that are
automatically generated by the android platform.
“R.java” is a generated class which contains references to resources of the
“res” folder in the project. These resources are maintained in the “res”
directory and can be values, menus, layouts, icons or pictures or animations.
For example a resource can be an image or an XML files which defines
strings.
If you create new resources, the corresponding reference is automatically
created in “R.java”. The references are static int values. The Android system
provides methods to access the resources. eg. to access a String with the
reference id “R.string.yourString” use the method
getString(R.string.yourString)); Please do not try to modify “R.java”
manually.

While the directory “res” contains structured values which are known to the
Android platform, the directory “assets” can be used to store any kind of data.
In Java you can access this data via the AssetsManager and the method
getAssets().
c.      /Android {version Number}
This folder contains the libraries (jars) needed for the project. In the
screenshot, you can see that it contains the framework jar file. This is similar
to the /lib folder which is present in any normal Java project.

d.     /res
This directory contains all the external resources (images, data files etc)
that are used by the android application. These external resources (content)
will be referenced in the android application.

This contains the following sub-folders
  • /res/drawable
  • /res/layout
  • /res/Values
i.        /res/drawable
This folder contains all images, pictures etc. If you want to include an
image or an icon in your android application, then you will be placing it in
this folder.
ii.      /res/layout
This folder contains the UI layouts that will be used in the project. These
UI layouts are stored as XML files. You can read more about it here.
iii.     /res/Values
This folder contains XML files which contain key values pairs that
will be referenced in the application. These XML files declare Arrays, colors,
dimensions, strings etc.
The main idea of having these values in a separate XML file is that the
values can be used based on the locale without actually changing the source
code. 
eg.  the messages in the application can be displayed in different languages
based on the use locale.
e.        /assets
This folder contains external resources used in the application like the /res
folder. But the main difference is that the resources are stored in raw format
and can be read only programmatically.

AndroidManifest.xml
This is an XML file which contains meta information about the android
application and is important file for every android application project. It
contains information about various activities, views, services etc. It also
contains the list of user permissions that are needed to run the android
application.

Back to the program…

7. Now open the file HelloAndroid > src > android.examples.helloandroid > HelloAndroid.java
Add the boxed lines to the already present code.



 8. Save HelloAndroid.java.
    That’s it! Our Hello World program is ready!!
9. Right- click the project in Package Explorer and select
   Run As > Android Application.



 The Eclipse ADT plugin also adds the project to the Applications screen.


 But this is not very impressive. Let’s add some more functionality to the
project.
We will add a label, a text box and a button. When the user enters his name
in the text box and clicks the button, application should display “Hello
<username>!”
Here’s how:
 1.     Adding resources
  Open the file res > values > string.xml. There are two views available.
 The xml view and the UI based view called Resources
  I find the xml view easier. It looks like this.


Note that Android has added the name which we see on the title as
“app_name” automatically.

To this file add the highlighted lines.



These are the resources which we will be using in our application. Save
this file.

2. Understanding and changing the UI

Next, open the layout > main.xml file.



Notice that there 3 main sections here.
- Rectangle 1 encompasses all the views and layouts available for building the
UI.
- Rectangle 2 shows how the UI will look. We can drag and drop the components
from 1 to 2.
- Rectangle 3 shows the choices available to us to switch between the Graphical
Layout view and the xml view.

We can either add the components to the view shown or code them in the xml
file.

3. Adding components to the UI

Now drag a “TextView”, an “EditText”, a “Button” and another
“TextView”(outlined in Blue) on to the screen in rectangle 2.



TextView01, EditText01, Button01 and TextView02 are the ids of the TextView,
EditText and the Button respectively. The “@+id/”  part tells the IDE to put
these values in the R.java class in the class id.

4. Configuring properties

Each component has some configurable properties associated with it, which we
can change.
Right click on the TextView01, select Show In > Properties.
A properties window should be displayed at the bottom.



The text property of the TextView01 will have the value @+id/TextView01. We
want to change it to “Enter your name : ”.
For this we can enter the string directly in the value column against Text or
alternatively, since we have added this string in the resources, click the
ellipse outlined in red. A Resource Chooser window will pop up.



From this, select lbl_username and click OK.

The main.xml screen will display “Enter your name :” instead of
@+id/TextView01.
  • Now, for EditText01, clear the contents in the Value column of the Text property, since initially this should be empty. Also set the Layout width under the Misc properties to “match_parent”.
  • For Button01, set the Text property to the resource “btn_text”. Also against the On click property, enter “btn_OnClick”. This is the handler for the On Click event of the button.
  • For TextView02, clear the contents in the Value column of the Text property.
Once this is done the main.xml should look like this.



Now save main.xml, clean and build the project.

5.     Handling Events
Next, open the HelloAndroid.java file and change the code to the
following.



We can use the "Ctrl+Shift+O" shortcut to import the required packages and
remove the unnecessary ones.

The btn_OnClick method will handle the button click event of the Click
Me button.
It checks if the user has entered a name. If yes, then it displays “Hello
<username>”, else it displays “Please enter a name.”

That’s it! The application’s ready. Right-click on the project and select
Run As > Android Application.
Also, remember that it takes a long time for the emulator to start for the
first time.
So DO NOT close it after you run it for the first time. You can make
modifications to the project and Right-click on the project and select Run
As
> Android Application and the project will run in the open
Emulator!