PhoneGap From Scratch: Introduction

PhoneGap From Scratch: Introduction

Tutorial Details
  • Technology: PhoneGap
  • Difficulty: Beginner
  • Completion Time: 45 - 60 Minutes
This entry is part 1 of 5 in the series PhoneGap From Scratch

Want to learn how to use PhoneGap, but don’t know where to get started? Join us as we put together “Sculder”, not only a tribute to an excellent science fiction TV series, but a fully-fledged native mobile application for the believer in you!

Sculder

In this series, we will build a mobile application using some of the features in PhoneGap. We will go from installation of the SDK to deployment into the app stores of the two major platforms: iOS and Android. Concepts covered in this series will include accessing the device camera, local storage, and geolocation.

In this first part, we will take a quick look at what PhoneGap actually is and what you can use it for, and then look at the installation of the PhoneGap framework and the SDKs that we require for testing on OS X, Windows, and Linux environments. We will then build and run the very simple “Hello World” PhoneGap application to ensure that we have everything running correctly.


What is PhoneGap?

By now you probably have a good idea of what PhoneGap is and you’ve probably even used it, but, if not, here’s a brief overview.

PhoneGap was born out of iPhoneDevCamp in 2008, where it was created simply because there were not a lot of Objective-C developers in comparison to Web Developers. The challenge was to put together a framework that would allow web developers to use HTML, CSS, and JavaScript to code applications that could take advantage of the native functionality of the mobile device, such as the Camera, Storage, and GeoLocation features. Initially built to work with the iPhone, within a year PhoneGap was growing and beginning to support Android too. Now, nearly 4 years old, PhoneGap is one of the most talked about toolkits for developing mobile applications and supports a much wider range of mobile devices including iOS, Android, Blackberry, Symbian, webOS, WP7, and Bada.

At the time of publication (e.g. January, 2012), the framework currently supports the Accelerometer, Camera, Compass, Contacts, File, Geolocation, Media, Network, Notifications (Alert, Sound, and Vibrate) and Storage device APIs. There is full support for all of these features in the newer iOS Devices (3GS+) and Android. For more details on support for Blackberry, WP7, Sybian, webOS, and Bada devices check the official compatibility table.

Despite contrary belief, PhoneGap is not a write once, deploy everywhere solution (although it does come close). It is certainly a cross-platform framework capable of running on many supported devices, but in order to deploy successfully you will likely need to test and tweak your code on each of the target devices.


Install & Hello World for iOS

If you want to develop for iOS, you will need an Intel based computer running MAC OS X version 10.6 or later. You will also need the latest version of Xcode (version 4 at the time of writing), and the iOS SDK for testing. In order to download Xcode, you’ll need to sign up as a member of the Apple Developer Program.

Head over to www.phonegap.com and in the top left hand corner you will see a button to download the latest version of PhoneGap. Clicking on this will prompt the download of a ZIP file containing everything you need to get started.

PhoneGap From Scratch

Unzipping the file will give you numerous folders, each labelled with the targeted OS. As we are installing for iOS, open up the iOS folder and mount the dmg file. The dmg contains a pkg file. Click this and go through the installation process. After completing the install, you can go ahead and start up Xcode and when you come to create a new project, you should be able to choose PhoneGap as a template.

PhoneGap From Scratch

We can now set the options for our project and the location of our files. Once we’ve done that, our project is built in the directory specified and Xcode presents us with our summary page. Here we can easily add app icons and change a couple of the settings when our application is ready to be packaged and submitted to the app store – for now we will just go ahead and hit RUN in the top left hand corner. This will compile the app and fire up the iOS simulator.

PhoneGap From Scratch

If you try this now, after the splash screen you should get an error stating that the index.html file could not be found. No need to worry, this is actually what should happen. We need to go the the working directory for the project (Right click on the project in Xcode and click show in finder) and there we will see a www directory in the project root.

PhoneGap From Scratch

We now need to drag that directory INTO Xcode and add it to the project.

PhoneGap From Scratch

In the options for these files we need to make sure that we select “Create folder reference for any added folders”, then click finish. Our www directory is now added to the project. We can now click run again and you will get the basic ‘Hello World’ for PhoneGap.

PhoneGap From Scratch

The www directory will now be our root directory for the app. This is where we will keep any HTML, CSS, or JavaScript that is going to be used by our app, just like you would expect for any other web application. The phonegap.js file is the JavaScript file that will act as our API, giving us access to the native APIs we might want to use in our application later.


Install & Hello World for Android

Unlike developing for iOS, you are able to develop for Android on any platform. Although it is advised that you use the Eclipse IDE with a couple of plugins, there is an alternative way to use PhoneGap (via Command Line), but it’s good if you start by doing it the longer way first with an IDE and then try out the command line way and see which one you prefer. In this tutorial we will be using the IDE method.

First, you are going to have to head to the Eclipse website and download the IDE for your platform of choice. The classic version is fine for what we need. Once downloaded, start Eclipse and we need to install the ADT plugin. You need to go to Help => Install New Software and click add in the right hand corner.

PhoneGap From Scratch

You then can enter ADT Plugin for the plugin name and enter the following for the repository URL.

https://dl-ssl.google.com/android/eclipse/

The plugin will download and install and Eclipse will prompt you to restart. Once it restarts you can create a new Android project.

PhoneGap From Scratch

You will then go through the project wizard where you will give your app a name and set up its workspace. you will also select your build target SDK – you can select the latest one for now (4.0.3 at the time of writing). Go through the rest of the wizard and set up the remaining information for the app.

You will be asked if you wish to download and install the required Android SDKs at this point. If you already have them on your machine, go ahead and browse to the folder. If not, you can let Eclipse download them for you.

Within the root directory of the application we need to create a directory called lids and within the assets directory create another directory called www. Now, back to the original PhoneGap file that was downloaded and in the Android folder you need to copy the phonegap.jar file to the libs directory we created and then copy the phonegap.js to the www directory.

Your structure should look like the following:

PhoneGap From Scratch

Within our www directory, create an index.html file and drop in the code below:

<!DOCTYPE HTML>
<html>
  <head>
    <title>mobiletuts phonegap</title>
  <script src="phonegap-1.2.0.js"></script>
  <script>
     function onLoad(){
          document.addEventListener("deviceready", onDeviceReady, true);
     }
     function onDeviceReady(){
          navigator.notification.alert("PhoneGap is working!!");
     }
  </script>
  </head>
  <body onload="onLoad();">
       <h1>Welcome to PhoneGap</h1>
       <h2>Edit assets/www/index.html</h2>
  </body>
</html>

Now we need to make some changes to the main Java file that can be found in the src folder. First, we need to change the class’ extend from Activity to DroidGap.. We then need to replace setContentView(R.layout.main); with super.loadUrl("file:///android_asset/www/index.html"); and then add import com.phonegap.*; after the first two imports. Your Java file upon completion should look something like this:

package com.shaundunneTest;
import android.app.Activity;
import android.os.Bundle;
import com.phonegap.*;
public class TestActivity extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

Eclipse will probably be throwing some errors now, just right click on the libs folder and go to Build Path => Configure Build Path and then in the libraries tab, click add JAR and go ahead and include the phonegap.jar file. This should clear up the errors. Now, we need to add some permissions to the manifest file to ensure that PhoneGap will run correctly.

Open up the AndroidManifest.xml file and add the following before the application entry:

<supports-screens
        android:largeScreens="true"
        android:normalScreens="true"
        android:smallScreens="true"
        android:resizeable="true"
        android:anyDensity="true"
        />
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.RECEIVE_SMS" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
        <uses-permission android:name="android.permission.READ_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

On the activity tag, add the following attribute:

	android:configChanges="orientation|keyboardHidden"

This ensures that the app doesn’t reload the index.html anytime those events happen.

The last thing to do is copy the xml folder from the PhoneGap download to the res directory in the project. You are now ready to run this in the emulator.

You can right-click your project now and run as an Android Application. If you haven’t set up a device yet, you will be prompted to do so, if you need help doing this, check out the documentation here

PhoneGap From Scratch

And that’s all you need to get started on Android!


What About All the Other Platforms?

So far, we have covered only two of the mobile platforms for our application, but it is likely that we would want to distribute across all the platforms that PhoneGap supports, right? Well, rather than go through installing a few more SDKs, another IDE with a few more plugins, and setup a Virtual Machine for testing, this series will use the PhoneGap:Build service when it comes time to distribute the app.

PhoneGap:Build, as it states on the website, is a cloud based service that will take a zipped up HTML/CSS/JS application and send you back the application, compiled and ready to go for distribution (one caveat: for Android, iOS, and BB you will need the required certificates for Distribution). PhoneGap:Build is in BETA at the moment, and while there are paid options (which are well worth having if you are going to be using it regularly), there is a free option that will allow one private application. That’s all we need for our project a the moment, so go ahead and sign up now as we will be using the Build service at the end of the series.


Concluding Remarks

We now have our environment ready for development with PhoneGap. In the next part of this series, we will start looking at the APIs that PhoneGap allows us to access and how to use them in our app.

Series NavigationPhoneGap From Scratch: Device APIs»

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Akkis

    Wow! Thank you very much! I start immedietly downloading! Keep writing great tuts!!

  • Arthur Mwai

    very helpful ♥

  • Leo

    Nice way to get started, I can’t wait for the rest of the series.

  • Darel

    Shaun, that was a great tutorial! But, the one thing that bothers me about this trend, is the fact that I have to use PhoneGap to deploy my app on multiple platforms. If I develop on ApplicationCraft, I have to use PhoneGap. If develop using Sensha Touch, I have to use PhoneGap. Deploying apps using SaaS software this way could be very expensive in the long run. Do I really need to go the PhoneGap route?

  • http://www.mmj-innovativ.de Marvin

    About time! I love PhoneGap. Can’t wait for some more in-depth tutorials.

  • Andres

    Hi, excellent tutorial, I have tried to do this, and everything went ok until I run it. the message i got in the android emulator is Hello World, MyEclipseProjectNameActvity!. what could be wrong, the alert you have in the index.html never shows up. Thank I hope you can help me.

  • Joshua

    I get the following error:

    “a network error occurred. (file:///android_asset/www/index.html)”

    thoughts?

    • Joshua

      nm. my fault! Works. Looking forward to more.

      • Hugo

        Hey Joshua how did you solve..
        “a network error occurred. (file:///android_asset/www/index.html)”

        Thanks

      • Andy

        Hey Joshua,
        Could you please tell me how you handled this error? I’ve been trying, but in vain..

  • http://www.chicswithaview.com Dawn

    When is the next series or step…I have nothing to do this weekend! ;D

  • http://partialbits.com Vamsi

    Hi !
    Excellent tutorial , but you have to mention about its limitations also ;)

  • CosinusWeb

    Really great tuts
    Keep going on I love that

  • Mat

    Does PhoneGap create true native applications or does it make applications within a webview and allow access to native features? I am currently learning appcelorator but like how PhoneGap is more closely comparable to web design.

  • Not working

    How to stop the network error….somebody??

    • amar

      I got this error because of wrong file name. Verify the name of the html file.

  • Apple

    First of all, great tutorial!! I don’t seem to be able to get the alert popup working for some reason. I followed the tutorial to every last word but can’t figure out what I’m doing wrong! Please help!

    • zitzu

      in the index.html file you need to change

      to

      or wichever is the name of the js file you put in the www/ folder.

      Zitzu

      • zitzu

        it was cut out but i mean to change the name of the .js file in the index.html according toi the phonegap javascript file you downloaded. Last wersion is “phonegap-1.4.1.js”

  • Fernando

    I tried to reproduce the example in Dreamweaver CS 5.5 but alerts not work, anybody knows why?

  • http://www.zendigital.com.au Chris

    This tutorial is exactly what I need, book marked for next weekend :) Thanks.

  • fotis

    for the new release to work you have to replace
    import com.phonegap.*;
    with
    import org.apache.cordova.DroidGap;

    • Jon

      Thanks for the tip with the new release, I knew that was the issue but wasn’t sure of the correct import.

    • kavin kumar

      thanks a lot

  • Jon

    Just another pointer:

    If anyone ran into the problem I did where the first run couldn’t build and spat out loads of errors, when you’re creating your new project, make sure that “Use Automatic Reference Counting” is UNCHECKED when you enter the project name.

  • Vinay

    Hey, I am trying to use phonegap for symbian app development. I am not getting the files from the phonegap and the documentation is very hard to understand.. Can anyone tell me the better way.. I am ready to use other framework instead of phonegap also.. Please guide me.. its so important and urgent !!

  • http://in.linkedin.com/in/anuraagsachdeva moha297

    The worst tutorial ever…. just copy pasted what was already there on PhoneGap website. http://docs.phonegap.com/en/1.8.1/guide_getting-started_index.md.html

    • http://www.rahulmishra.com Rahul

      Whats a looser you are. Can’t you see his effort behind the tut? Buses don’t go where you stay. huh?

  • Sharavan

    Alert does not work…any clues.

  • http://www.moreyaa.com Jayman Pandya

    Kudos to Shaun for writing this brilliant Series, but this Tutorial cannot to be followed now as PhoneGap has updated on how to setup the development environment.

    It no longer has a dmg to install but you have to go through Command Line tools to install the Apache Cordova 2.1.0

    You can get info on this link : http://docs.phonegap.com/en/edge/guide_getting-started_index.md.html#Getting%20Started%20Guides

    It will be great if Shaun can edit this and update the new process. This is a very helpful resource to learn PhoneGap and will definitely help more and more people.

    Thank You again Shaun… :)

  • Redscrapbook

    I agree with Jayman Pandya and it is urgent update as the above tutorial is now useless, unfortunately (I’ve used tutplus for a lot of tutorials) as .dmg is no longer required for Phonegap 2.0 and Phonegap 2.1. I’ve awful experience with phonegap so far see:
    http://stackoverflow.com/questions/12716830/xcode-4-5-no-such-file-or-directory-libcordova-a/12805058#comment17331979_12805058

    A new tutorial is urgent as a lot of people experience the same.

    Send me email : redscrapbook [DOT] yahoo [DOT] co.uk if there is a new tutorials for Phonegap 2.1 and all the trickery as the above link so far to no avail.

  • Jhon

    Hi, I think there’s a typo error.. Lids or libs?

    I love this tutorial, simply amazing! Thank you!

  • http://twitter.com/_voycie Dan Voyce

    Can someone tell me if these tutorials are still all valid with the latest version of phonegap / Cordova?

    • Emmet

      I just completed it, it seemed to all work except in a few places you just had to change the name from “PhoneGap” to the Cordova name, although the project is not building. When I press run as Android app it doesn’t do anything, no prompt, error, nothing.. Anyone experience this?

    • rocks

      yes valid..instead i would say that they are much apt..
      i followed them..it works

    • mozillanerd

      I used the latest from GitHub which is phonegap-2.7.0rc1. For Android (in the android folder) minor name changes to cordova-2.7.0.jar and cordovar-2.7.0.js where necessary as well as Build Path changes (adapted for the names). Use the ‘Quick Fix’ to get rid of errors in Eclipse. I have used
      Eclipse IDE for Java EE Developers,instead of Classic version in order to get more editors including a Web Page editor

  • Khaled

    This tutorial needs to be updated in order to be valid for the latest version of Cordova

  • angry_student

    This tutorial is outdated. It needs to be removed!

  • Vlad P.

    As mentioned below, the tutorial is quite outdated. For those who wish to get started and at least build a sample project, this guide will help:
    http://www.adobe.com/devnet/html5/articles/getting-started-with-phonegap-in-eclipse-for-android.html

    It covers PhoneGap / Cordova 1.5, but it is valid for version 2.4 too.

  • Mark Scovel

    I just completed the hello world for android on this page and it worked. My notes are below

    followed these instructions first (down to “Deploy to Emulator”):
    http://docs.phonegap.com/en/2.4.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

    Notes:
    1. Had to add JAVA_HOME to system env variables
    2. uninstalled all java and installed JDK
    3. added to path:
    ;C:Program FilesAndroidandroid-sdk;C:Program FilesAndroidandroid-sdkplatform-tools;C:Program FilesAndroidandroid-sdktools;%JAVA_HOME%bin;F:developmentapache-ant-1.8.4bin

    then followed these instructions: on this page above
    http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
    and it worked.

    Notes:
    1. once the android virtual device displays, it still takes more time for the home screen to show so wait until that has happened before launching the eclipse project on it.
    2. had to download phonegap 1.2.0 as the tutsplus referenced above seems to be based on that.
    3. “public” was missing from void onCreate(Bundle savedInstanceState) so add it in front

  • sandra

    for anyone that’s having trouble: my path for index.html was actually not in a folder called android_assets but instead just assets. so make sure to double check before pasting this line! super.loadUrl(“file:///android_asset/www/index.html”);

    • kavin kumar

      thank u very much this solved the mystery

  • gen_2000

    hi, i am following your instruction but stuck somewhere:

    just right click on the libs folder and go to Build Path => Configure Build Path

    I couldn’t find Build Path when right clicked on libs folder?

    Please guide.

  • http://www.facebook.com/val.sorrento Val Sorrento

    Thanks for the excellent tutorial.

  • mozillanerd

    The Classic version of Eclipse does not have appropriate editors for HTML(5) or JavaScript