Creating an Android “Hello World” Application with PhoneGap

Creating an Android “Hello World” Application with PhoneGap

Tutorial Details
  • Technology: PhoneGap + Android
  • Difficulty: Beginner
  • Completion Time: 30 - 60 Minutes

PhoneGap is an open source platform that allows you to create cross-platform mobile applications with HTML, JavaScript, and CSS. In order to interact with device hardware, PhoneGap provides a JavaScript API that will interface with features such as the on-board camera, GPS, and accelerometer. Even though PhoneGap is great for developing cross-platform applications, the code for developing applications while targetting one platform or another will vary. One of the greatest differences to overcome is the required software requirements. This tutorial will provide an in-depth review of setting up your development environment for Android, and will build a simple “Hello World” app.

PhoneGap Requirements for Android Development

Java JDK

You will need to install the Java Development Kit (JDK). Follow the official instructions for setting this up.

Android SDK

You will also need the Android Software Development Kit. When you install the SDK, you will need to set the the android-sdk-<os>/tools for your user PATH variable.

System Properties

Eclipse

You will need to download and install Eclipse if you don’t already have it on your machine.

Eclipse ADT Plugin

You will need to also install the ADT plugin for Eclipse. ADT (Android Development tools) is a plugin of eclipse which provide a complete IDE for developing Android application. ADT lets you create new Android projects, and it lets you create Android projects from existing source (this is the way we will open our PhoneGap app for android on eclipse). Using ADT you can also debug an android application. As ADT is well integrated with android SDK running the app from the IDE directly launches the android emulator.

To install ADT click on “install new software” in your Eclipse’s help window and enter the following site to work with: http://dl-ssl.google.com/android/eclipse/. Then follow the wizard presented to install ADT.

ADT Screen

Android Platforms and Components

Once you have ADT installed, you will need to install the Android platform and other components. To do that, go to menu option window->Android DK and AVD manager and select the platform and API level. Android api 2.2 is latest at the time of writing this article.

ADT Configuration

Apache Ant

If you don’t have apache ant installed you can download it from http://ant.apache.org/bindownload.cgi. To install it you will just extract the downloaded Zip file and set the bin folder in the ant directory in you PATH variable.

Ruby

If you don’t have Ruby installed, you can download it from this free installer. Once installed, add the Ruby/bin path into your account’s PATH variables.

PhoneGap Framework

Of course, you will also need the PhoneGap Framework itself.

PhoneGap-Android Download

Creating Your Development Workspace

Environment Variables Check:

The following paths should be set in you account’s PATH variable:

  • your_system_path/jdk/bin
  • your_system_path/android-sdk/tools
  • your_system_path/ruby/bin
  • your_system_path/apache-ant/bin

Apart from these, you will need to set the following variables also:

  • JAVA_HOME – path of your JDK directory
  • ANT_HOME – path of you apache-ant directory
  • ANDROID_HOME – path to your android SDK directory.

To create a workspace for your PhoneGap app on android, go to the “phonegap-android” folder on the command prompt or terminal:

ruby ./droidgap "[android_sdk_path]" [name] [package_name] "[www]" "[path]"
  • android_sdk_path: Where you installed the SDK
  • name: The name to give the new application.
  • package_name: The name you want to give to your application.
  • www: The folder from where you want to copy the files of your PhoneGap app.
  • path: The application workspace for your project.

Once you run the command and if everything goes correct messages as shown below will be seen:

PhoneGap Command Line Android

The above should create a complete workspace for your PhoneGap Android app.

Workflow

Setup Your Project in Eclipse

Once this is done, this workspace can be opened in eclipse. In eclipse choose new project and then choose Android Project.

Create Android Eclipse Project

Next select “create project from existing source” and give the project a name as shown below.

Configure an Android Eclipse Project

If you try to build and run the project in Eclipse you will get a build error. This is because you have not added the external library (phonegap.jar) which is created in the libs folder of your workspace.

Remove Build Errors

To add that external library right click on the project an select Build Path-> Add external archive and then select the phonegap.jar in your libs folder.

Remove Build Errors 2

If all goes well, this should remove all the build errors in your project. Now try to run your project in the emulator. You should see the screen below. This is because you have not added any PhoneGap HTML or JavaScript files in your project.

Running the Hello World App

In the assets/www folder of the workspace, there will already be a file called phonegap.js. In that folder create a file called index.html with the following code:

<!DOCTYPE HTML>
<html>
  <head>
    <meta name="viewport" content="width=320; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>PhoneGap Android App</title>
              <script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
              <script type="text/javascript" charset="utf-8">
                        var showMessageBox = function() {
                             navigator.notification.alert("Hello World of PhoneGap");
                        }
                        function init(){
                             document.addEventListener("deviceready", showMessageBox, true);
                        }
  </script>
  </head>
  <body onload="init();"  >
  </body>
</html>

In the code the line:

<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>

includes the phonegap.js file which lets you call native API’s of android. On the load of the body the init function registers the function showMessageBox on the PhoneGap event deviceready which is triggered when phonegap has done the processing to initialized everything for your program so that it can call the PhoneGap API’s. The showMessageBox function calls the PhoneGap API navigator.notification.alert which displays the messagebox on screen. Running the app after adding the index.html and refreshing the project in Eclipse you will see the following screen:

Making it an Alert

Now let’s add some more functionality to our app. The following code creates a text box to enter the name of the person and a button when clicked displays a message box:

<!DOCTYPE HTML>
<html>
  <head>
    <meta name="viewport" content="width=320; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>PhoneGap</title>
              <script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
              <script type="text/javascript" charset="utf-8">
              var displayHello = function() {
                        var name =      document.getElementById("firstname").value;
                        navigator.notification.alert("name" + name);
            }
   </script>
  </head>
  <body onload="init();" id="bdy" >
            <div id="txt">
            <input   type="text" name="firstname" id="firstname" />
            </div>
            <div id ="btn">
    <a href="#" class="btn" onclick="displayHello();">Say Hello</a>
            </div>
        </div>
  </body>
</html>

In the following line of code we have created a text box where you can enter your name.

<input   type="text" name="firstname" id="firstname" />

In the line

     <a href="#" class="btn" onclick="displayHello();">Say Hello

We have created a link which on click calls the function displayHello which fetches the value from the text box and displays a message box saying hello to the name entered by the user.

Custom Alert Text
Final Preview

The GUI shown above does not have any styling to it. You can beautify the display and add colors to it using a CSS file. Create a master.css in your assets\www folder with the following code:

#bdy
{
            background:#F0F0F0;
}
#btn a{
            border: 1px solid #555;
            -webkit-border-radius: 5px;
            border-radius: 5px;
            text-align:center;
            display:block;
            float:left;
            background:#6600CC;
            width:308px;
            color:#FFF;
            font-size:1.1em;
            text-decoration:none;
            padding:1.2em 0;
            margin:3px 0px 3px 5px;
}
#txt{
            border: 1px solid #555;
            -webkit-border-radius: 5px;
            border-radius: 5px;
            text-align:center;
            display:block;
            float:left;
            background:#00FFCC;
            width:308px;
            color:#9ab;
            font-size:1.1em;
            text-decoration:none;
            padding:1.2em 0;
            margin:3px 0px 3px 5px;
}

In your index.html add the following line before in your head tags to link to master.css:

<link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8">

Now if you run the app you should see a screen like the following:

Final Preview

Conclusion

To create a PhoneGap app on Android, a lot of different software has to work together. This could mean that you could have trouble setting up the complete environment to create a PhoneGap app on Android. However, once all the software is in place, you can easily create PhoneGap apps using open web standards like HTML, JavaScript, CSS and PhoneGap’s own API’s to perform device hardware specific processing. This saves you the trouble of learning the native language for Android programming and still has much of the power of custom, native built Android apps.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://mo7amedfouad.com Mohamed Fouad

    Great Post .. i wish if you could do it for blackberry i tried more than 3 times to do it and failed :(

  • http://dariux.com Dario Gutierrez

    Hey Abbas, great tut, but , Is this posible to do in Mac OS X? Thanks and congratulations.

  • http://wedesignapps.com Christopher Chance

    Hey,
    Nice tutorial. I have been getting my hands dirty with phonegap recently. Unfortunately its too much hassle just to get the setup going on with the various versions of android sdk, phonegap versions and environment variables. Too many folks have “Build Failed” problem. I have tried all possible scenarios but still no success in getting it to work. Can you please throw some light on the exact versions you have used here.
    Although the phonegap site lists all possible errors there is no straightforward solution to any of these problems.

  • uorp

    c’mon guys is not so difficult

    ruby 1.9.1

  • Silver Charms

    Great post.
    Just keep it up.

  • kodeninja

    Abbas,

    Aren’t you missing things like code completion, static typing, unit testing and other benefits of the Java programming model, while working with PhoneGap? JS support in Eclipse clearly isn’t even near to that of NetBeans. What’s your experience building an app in pure JS, as opposed to doing it in Java?

  • Francisco

    Great tutorial!!!!! thanks
    You used to contact phonegap api?
    I’m trying to run the example that brings phonegap but I get the following error:::
    ‘Navigator.ContactManager’ [undefined] is Not an object.

    I hope someone can help me

  • http://www.pixeltalents.com Sylvester

    I was getting lot of error messages and since there are so many discussions about it on google groups, maybe you could add a few hints to those windows users who get errors as well:

    - droidgap file has to be modified (‘.bat’ needs to be added to ‘ant’ and ‘android’ commands)
    - you MUST use forward-slashes

    This might save somebody else a lot of time ;-)

  • Edison A. Leon

    Great tutorial and yes, it’s hard to install all the software, but I think I’m gonna try. I had tried appcelerator, and I was successful creating apps. Unfortunately I have failed loading my samples in an android device or iphone device which is sad cause I can not test anything in a real device. I’m eager to find out what’s the good in phonegap world so wish me luck.

  • stonehat

    Also stuck with errors during the incredibly clumsy install process.

    Phonegap guys: If you’re clever enough to write a cross-platform IDE that I should use, how come you’re not clever enough to write an Install app for it ?

    • Zachary Kent

      My thoughts exactly.

  • http://www.24x7code.com Rahul

    Nice post .. This is really helpful for newbies like me ..

  • helle

    I keep getting this error: the ./droidgap command not being recognised by ruby :-( and later – no SDK Target listed when I try to create an android-project in eclipse

  • http://uploadnsell.com Iszuddin Ismail

    FOR THOSE HAVING PROBLEMS BUILDING THE PHONEGAP-ANDROID PLATFORM

    I was having a really hard time trying to setup my PhoneGap-Android platform, especially with Ruby and DroidGap. I build it, build it again. Upgrade versions, downgrade versions. Downloads, setup… more download setups. Nothing works. Then when I write my problem to PhoneGap Google Group, Nick McCloud responded…

    Skip the ruby and droidgap and just follow this…

    http://wiki.phonegap.com/w/page/30862722/phonegap-android-eclipse-quickstart

    Now I am building Android apps with PhoneGap…. wooohooo … !!!

    By the way, nice tutorial Abbas. Now trying to figure out the Camera and File Upload plugin.

    Another thing, those starting out with PhoneGap for Android, try getting Building Android Apps with HTML, CSS, and Javascript by Jonathan Stark (O’Reilly). Quick guide, straight to the point. It’s a good start for me.

    • Hash

      Hi there,

      I followed the PhoneGap wiki for running the sample application for Android platform too (http://wiki.phonegap.com/w/page/30862722/phonegap-android-eclipse-quickstart). It is a kind of work but I got some problem. The sample application can only be run on Android emulator for a few seconds.

      After that, the emulator is always close that sample application and return to the main Android applications page. This always happen. No matter what I tried to create new application from scratch by including phonegap.js and phonegap.jar and creating a simple HTML page which include phonegap.js.

      Cheers,

  • Zachary Kent

    So no matter what I do, I get the “Hello World, ” instead of the contents of my index.html file. It must not be building properly and sending out the AndroidExample.apk file that is already there. Any suggestions?

  • kusuma

    Very nice tutorial!! :)

  • http://www.petzooey.com Awesome

    Great tutorial – You wouldn’t happen to know how to switch to a new Activity subclass or DroidGap subclass on an event click would you? Thanks!

  • Murali Krishna

    Hi ,

    This is very good artiecal . Could you please let me know how to make call to RestFul web service from Andriod Phone using PhoneGap?”

  • munna

    Hi Iszuddin Ismail ,

    i followed according to the instruction given in that tutorial . But even though i’m not gettting the Alert message of phonegap initaited

    i failed to work on phonegap configuration and also failed to tried on the link you have provided in the forum..

    please suggest me how can i do the exact configurations on this phonegap. because i need to work on camera option and fileupload..
    please help me on this

    thanks in advance

    Regards,
    Munna

    • http://www.patrickrauland.com Patrick

      Make sure you have the right src for the js file. I had my script tag pointing to phonegap.js but the file name was actually phonegap.0.9.4.js. There was a forehead smacking moment. :)

  • olmoe

    Thats great!
    cr8tingapps for dummies – and that’s what i needed; i feel like an application-development company ;)
    I’m looking forward seeing more of this.

  • Chris

    Can we deploy the application you made above in the form of .exe. I mean rather than asking user to go to the pecific URL I want them to just click to the app Icon and they can see the application

  • sushan sharma

    hello sir/mam,
    i need the download link or ppt for hello world example.

  • levani

    Can I use Aptana 3 instead of Eclipse?

  • http://this1that1whatever.com David

    I followed the instructions at http://www.phonegap.com/start#android and was able to get a simple web app created – 3 html pages. It was very important to complete the AndroidManifest.xml changes because without it, Other Page did not work. I also incorporated Sencha Touch into my sample app by copying sencha-touch.js and sencha-touch.css into my Elipse project workspace.

  • Rajesh

    hi this post helped me,

    could you please let me know how to invoke a web service using jQuery in phonegap .

    thanks in advance.

  • sudhi

    Hi,

    how to make css3 to work on android phones?

  • Nagaraj

    Is it possible to convert a pure web application to native mobile app using PhoneGap…? without writing web services for that. Or we should have a web service for our app ,using the web service in phoneGap we can create a native app using css ,Jquery,Javascript…?

  • Dennis

    Greate Job!
    Very detail about phongap setup.
    thks

  • Abhishek

    Hey abbas this is very helpful to me thank for posting this type of forms……..

  • http://drumbeat.pro Zeal

    I can’t get it to generate the files, somehow I am failing to type the correct code in the terminal. Please help with punctuation and show examples if possible. Most about the part below:
    ruby ./droidgap “[android_sdk_path]” [name] [package_name] “[www]” “[path]”

    Kindly show an example I have been trying:

    C:\Users\drumbeat\Documents\Steller\tools\phonegap\Android>ruby ./phonegap “C:/Users/drumbeat/Documents/Steller/tools/androidsdk” droid2 com.droid2.app “www” “C:/Users/drumbeat/Documents/Steller/tools/phonegapp”

  • stanger

    really bad post no commonsense just screenshot practically not possible.hi ha ha ha ha!!!!!!!!!!!!!1

  • Getting Bored

    Please provide an example to start one activity from another activity using phone gap.

  • rickky ross

    Those guys who are facing Build error try property->java Build path->Add External Librarys to ur library there and enjoy hassle free phonegap experience.
    Rickky Ross
    San Jose

  • KAKAROT

    HI, i try to inderstand haw phonegap is a cross-platform, i mean if i develop an application under eclipse(android) haw can i get the ios apps, i tryed the phonegap build tool, by zipping my (android/phonegap project) but it did ‘t work ,

  • http://sushilbharwani.blogspot.com sushil bharwani

    Thanks i liked the explanation and built my first Android App.

  • Somuraja

    Hi,

    I have created app for my url using phonegap.

    If i have update my url it not reflect in my app.

    can you explain how to create app for web url and it should get reflect in my app

  • http://newsamsunggalaxys3cellphone201248.page.tl GalaxyS3 overview official

    It’s actually a great and helpful piece of information. I’m happy that you simply shared this helpful information with us. Please keep us up to date like this. Thank you for sharing.

  • Sanjeet Singh saini

    Is it possible in android window7 platform ……???????

  • Eman

    Is it possible to host: “http://blah.blah.com” site which has assets pointing to local file system? (using Phonegap of course)

  • Aadam Gibson

    Awesome post, all details are provided in your blog and I like explanation of phonegap.

  • buzzermobi.info

    This is a great post. Thanks so much for sharing, like always.

  • Siddharth Sharma

    Hi

    I am getting an error

    ruby:no such file or directory –./droidgap (loaderror)

    • http://www.facebook.com/herchizante Javier Herrador Rodríguez

      me too

  • Herchi

    and why not to use only android sdk to create a hello world?

  • http://twitter.com/hdpavan pavan deshpande

    Very nice tutorial you can also check this one

    http://pavanhd.blogspot.in/2012/09/android-hello-world-example.html

  • pawan

    very nice tutorial you can also check this one
    http://pavanhd.blogspot.in/2012/09/android-hello-world-example.html