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!

 



Tuesday, February 8, 2011

Getting started with Android!

Introduction
Android, as everyone should be knowing by now, is Google’s mobile platform, which is overtly loved and appreciated by developers, geeks, critics as well as foodies (like me ;-)... since Android products are named after desserts). The global smartphone market is booming, and Google's Android platform was leading the pack during the fourth quarter 2010, according to a recent report issued on Monday by Canalys Smart Phone Analysis services.
Android is an operating system based on Linux with a Java programming interface. It provides development tools (compiler, debugger, device emulator, etc.) as well as its own virtual machine called the Dalvik Virtual Machine – DVM (analogous to Java Virtual Machine). Android is created by the Open Handset Alliance which is lead by Google.
Dalvik uses special bytecode. Therefore you cannot run standard Java bytecode on Android. Android provides a tool "dx" which allows to convert Java Class files into "dex" (Dalvik Executable) files.
Android applications are packed into an .apk (Android Package) file.
To simplify development Google provides the Android Development Tools (ADT) for Eclipse . The ADT automatically converts from class to dex files and creates the apk during deployment.
Android supports 2-D and 3-D graphics using the OpenGL libraries and supports data storage in a SQLite database.
Every Android application runs in its own process and under its own userid which is generated automatically by the Android system during deployment. Therefore the application is isolated from other running applications and a misbehaving application would not easily harm other Android applications.
Let’s get started!!!

Steps for installation and configuration of the device
1. If you have Eclipse 3.4 Ganymede or greater, proceed to step 2. Else you need to download Eclipse
     Classic from here.
2. Download the Android SDK starter package from here. I recommend that you download the .exe package
     (for Windows).
 If you downloaded a .zip or .tgz package (instead of the SDK installer), unpack it to a location on your  machine. By default, the SDK files are unpacked into a directory named android-sdk-<machine- platform>.
 If you downloaded the Windows installer (.exe file), run it and it will check whether the proper Java SE  Development Kit (JDK) is installed (installing it, if necessary). Then install the SDK Tools into a default  location.
 Make a note of the name and location of the SDK directory on your system—you will need to refer to 
 the SDK directory later, when setting up the ADT plugin for Eclipse.

3. Using Eclipse, install the Android Development Tools. Detailed steps for installing the ADT are given  
    below:
    If you have Eclipse 3.4 (Ganymede):
   a)      Start Eclipse.
   b)      Select Help > Software Updates.
   c)      In the dialog that appears, click Available Software tab.
   d)     Click Add Site.
   e)      In the dialog that appears, enter https://dl-ssl.google.com/android/eclipse in the Location field and
           click OK.
   f)      Back in the Available Software view, you will see the plugin listed with Developer Tools nested
           within it. Select the checkbox next to Developer Tools and click Install.
   g)     On the next installation window, all of the included tools should be checked. Click Next.
   h)     Read and accept the license agreement, then click Finish.
   i)      Once installation completes, restart Eclipse.

Alternatively, if you are using Eclipse 3.5 (Galileo) or Eclipse 3.6 (Helios):
   a)      Start Eclipse.
   b)      Select Help > New Software.
   c)      Click Add in the top right corner.
   d)      In the dialog that appears, enter ADT Plugin in the Name: field.
            Enter https://dl-ssl.google.com/android/eclipse in the Location: field. Click OK.
   e)      In the Available Software view, select the textbox next to Developer Tools and click Next.
   f)      Follow the steps g, h and i listed above.

4. Once the tools have been downloaded, next step is to Configure the ADT plugin.
   a)      Start Eclipse.
   b)      Select Windows > Preferences.
   c)      Select Android in the left hand side list.
   d)     Browse to the location of the Android SDK directory.

   e)      Click OK/ Apply.

5. Now select Window > Android SDK and AVD Manager.


Select Available Packages. Select the latest version of the SDK.


Click Install Selected, confirm license. Once installed, restart Eclipse.

6. Now we need to configure the device which will be used for emulation.
    For that, click the Device Manager button.
    
 
   Select Virtual Devices and click New…         

   

   Enter the following:


Click Create AVD.
To test if the setup has been done correctly, select your device and click Start. 
Have patience. The device takes a long time to start.

Thats it... Now we’re ready to build our first project!!!