Building a PhoneGap Android App in Windows: Cordova 2.2.0 with Eclipse 4.2.1


Install Eclipse Juno IDE

Eclipse is an IDE (integrated development environment) for creating a variety of applications. Download Eclipse Classic 4.2.1, Windows 32-bit, from: http://www.eclipse.org/downloads/. 222MB download. It went into my Downloads folder. I unzipped it and put it in my C:/Program Files/eclipse folder. I right-dragged the eclipse.exe file to my desktop and designated it a Shortcut.

On startup, it asked me to set up a workspace:
C:\Documents and Settings\shusting\workspace
I opted for that location to be the default. After it started up, I exited.

Install Java JDK

We need the Java JDK (Java development kit), which includes the much-needed JRE (Java runtime environment) as well. Oracle Java is a programming language used to make programs that run across a wide variety of computer operating systems, printers, cell phones, home appliances, credit cards, cable boxes, and many other applications.

1. Install it from: http://www.oracle.com/technetwork/java/javase/downloads/index.html
I chose Java Platform (JDK) 7u9. It took me to the next page to download for the proper operating system. I accepted the license agreement. I went to http://support.microsoft.com/kb/827218#method2 to find out whether I had 32-bit or 64-bit, then chose the Windows x86 download.
2. When the Java SE (Standard Edition) file was downloaded, I double-clicked on the executable file, then answered in the affirmative to all the defaults.
3. Javac (Java compiler) is also needed, but I assume it’s part of this distribution.

Install ADT

The page following talks about the ADT (Android Developer Tools + Eclipse bundle), and gives the link to download the software. Read the system requirements section to get an overview of the steps we’ll be taking:
http://developer.android.com/sdk/index.html

We’ve already downloaded the Eclipse IDE, so scroll down for the link for “Use An Existing IDE” and download from there. It requires the JDT (Java development tools), but that was already included in our Eclipse download in its plugins folder (as org.eclipse.jdt.debug).

This page gave a little more information on setting up the files, which we will follow next:
http://developer.android.com/sdk/installing/installing-adt.html

1. I successfully unzipped and stored it at C:/Program Files/adt-bundle-windows.
2. Start Eclipse, then select Help > Install New Software.
3. Click on Add in the top-right corner.
4, In the Add Repository dialog that appears, enter “ADT Plugin” for the Name and the following URL for the Location:

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

5. Click OK. If you have trouble acquiring the plugin, try using “http” in the Location URL, instead of “https” (https is preferred for security reasons).
6. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
7. In the next window, you’ll see a list of the tools to be downloaded. Click Next.
8. Read and accept the license agreements, then click Finish. If, during the install process, you get a security warning saying that the authenticity or validity of the software can’t be established, click OK.
9. When the installation completes, restart Eclipse.

Install the Android SDK

Android provides its own SDK (software development kit) to help us build applications that run in the Android environment.

1. When I restarted Eclipse in the last section, a warning popped up telling me the the “Location of the Android SDK has not been setup in the preferences.” I clicked on the Open Preferences button.
2. In the popup, decide whether you’ll send usage statistics to Google or not and click Proceed.
3. I navigated in the Browse File to C:/Program Files/adt-bundle-windows/sdk
4. Click on Apply. An SDK Target will appear in the panel for the Android Preferences. In my case, Android 4.2, API level 17.
5. Click on Apply again, then OK.
6. There was a Welcome to Android Development window waiting for me, requesting the SDK location. I decided to Install new SDK and checked both boxes under that option.
7. Click Next and decide if you want usage stats to go to Google. Click Finish.
8. Select Accept All and Install to begin the long download. Whew! Almost done.
9. An alert in Eclipse informed me that an update was available. I clicked on the notice and answered positive to the next few prompts, then restarted Eclipse.

Android SDK Manager

Android SDK allows us to choose which level of API we want to develop for and preview in a emulator.

1. Go to Window > Open Perspective > Other… and choose Java.
2. Go to Window > Android SDK Manager.
3. I selected API 17, 16, and 8). Go ahead and select any other packages you know you’ll need (if you already have apps created that need particular APIs). Also review the package “Extras” to see if you need any of those.
4. I clicked on the button saying, “Install xx packages..”
5. I clicked on the Accept All radio button, then on Install. This may take 15-45 minutes, depending on which packages you chose.
6. Exit the SDK Manager (click on the red light at upper left) and click on Help > Check for Updates to look for updates to the the software you just downloaded. This process will take several minutes. I did not wait, but went right into downloading and installing Cordova, next section. Don’t be fooled by the progress in percentages – that is per file, not for the complete download!

Download Cordova 2.2.0

1. From http://www.phonegap.com, I downloaded version 2.2.0 (26.2MB), released Nov. 1, 2012. A list of its upgrade changes can be found here.
2. It was downloaded to my Downloads folder as: phonegap-phonegap-2.2.0-0-g8a3aa47.zip I extracted it to D:/PhoneGap/phonegap-phonegap-2.2.0-0-g8a3aa47
3. In the phonegap.com download page, I clicked on Getting Started Guides, then chose Getting Started with Android. We will follow those steps in the next section.

Set up your PATH environment variable

1. Right-click on (not open) My Computer on the desktop, and click Properties. (If you don’t have the My Computer icon, go to Start > Control Panel > System.)
2. Click on the Advanced tab, then the Environment Variables button.
3. Select the PATH variable from the System variables section. Do not select the CLASSPATH or PATHTEXT lines.
4. Select the Edit button.
5. You need to add the path to your Android SDK platform-tools and tools directory. If you had placed your folder in the same place as I did earlier, append the following text into the text box:

;C:\Program Files\adt-bundle-windows\sdk\platform-tools;C:\Program Files\adt-bundle-windows\sdk\tools

6. Click OK to save your edit.
7. Additionally, you may need to include %JAVA_HOME%\bin to your PATH as well. To check to see if this is required, click on Start, then on Run…, and type java into the field. If it cannot be found (if the control box opens then closes abruptly), follow steps 2-6 above and add the following to the PATH:

;%JAVA_HOME%\bin

The Cordova instructions tell us, “You may need to specify the full path instead of using the %JAVA_HOME% environment variable.” I entered my full path: C:\Program Files\Java\jdk1.7.0_09\bin. This is also the location of the javac (Java compiler, javac.exe) file, which is a good thing.
8. You may need to include %ANT_HOME%\bin to your PATH as well. (About Ant: Apache Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. According to Ant’s original author, James Duncan Davidson, the name is an acronym for “Another Neat Tool.”) To check to see if this is required, click on Start, then on Run…, and type ant. If the program cannot be found, add %ANT_HOME%\bin to the PATH. In my case, a window opened up showing the files. The full path in my case was: C:\Program Files\apache-ant-1.8.4\bin
9. Close the Environment Variables dialog and System Properties box.
10. Check in the console that you have the paths set by putting -version after the names. Below is what I entered and what the command prompt returned:

java -version
java version “1.7.0_09”
Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
Java HotSpot(TM) Client VM (build 23.5-b02, mixed mode, sharing)

javac -version
javac 1.7.0_09

ant -version
Apache Ant(TM) version 1.8.4 compiled on May 22 2012

Set Up Your PATH, summary

In a nutshell, this is how I set up the environment variables. Your folder locations and folder names may vary.

===ADT===
1. Get addresses where you installed these ADT folders:
C:\Program Files\Android\adt-bundle-windows-x86_64-20131030\sdk\platform-tools;
C:\Program Files\Android\adt-bundle-windows-x86_64-20131030\sdk\tools;

2. Open Environment Variables panel (Start > Control Panel > System > Advanced tab > Environment Variables… button).
System variables > New… button, then scroll down to see “Path” variable and click on it. Click on Edit… button and add to end of statement the two folder addresses above:
C:\Program Files\Android\adt-bundle-windows-x86_64-20131030\sdk\platform-tools;C:\Program Files\Android\adt-bundle-windows-x86_64-20131030\sdk\tools;

===JAVA===
1. Get address where you installed the Java /bin folder:
C:\Program Files\Java\jdk1.7.0_45\bin

2. Open Environment Variables panel (Start > Control Panel > System > Advanced tab > Environment Variables… button):
User variable, New… button, then:
Variable: %JAVA_HOME%
Value: C:\Program Files\Java\jdk1.7.0_45\bin

3. Lower down: System variables > New… button, then scroll down to see “Path” variable and click on it. Click on Edit… button and add to end of statement: %JAVA_HOME%;

4. Verification in console:
Type: java -version
Response: java version “1.7.0_45”

===Ant===
1. Download ant:
http://ant.apache.org/bindownload.cgi

2. Create folder and copy zipped files to it:
C:\Program Files\apache-ant-1.9.4

3. Open Environment Variables panel (Start > Control Panel > System > Advanced tab > Environment Variables… button):
User variable, New… button, then:
Variable: %ANT_HOME%
Value: C:\Program Files\apache-ant-1.9.4\bin

4. Lower down: System variables > New… button, then scroll down to see “Path” variable and click on it. Click on Edit… button and add to end of statement:
%ANT_HOME%;

5. Verification in console:
Type: ant -version
Response: Apache Ant(TM) version 1.9.4 compiles on April 29 2014

Set Up Your Projects’ Cordova Files

Cordova will create the important files for your project via the console.

1. Open a command prompt: Go to Start, Run…, and type cmd.exe to open the command prompt console window.
2. Navigate to the \bin directory within the Android subfolder of the Cordova distribution. In my case it was:
D:\PhoneGap\phonegap-phonegap-2.2.0-0-g8a3aa47\phonegap-phonegap-8a3aa47\lib\android\bin
If you look in the /bin folder, you’ll see the “create” file there that will execute the following command.
3. Decide on:
a. the path where your project will reside (like D:\Android\newProject)
b. the package name (like com.stevehusting.newProject)
c. the project name (newProject; no dashes allowed).
Put all four pieces of information together:
create <Android_bin_path_to_create_file> <project_folder_path> <package_name> <project_name>
(Do not include the < or >.)
My phonegap files resided on my D: drive, so I entered D: to change to that drive.
4. Once the command prompt started with D:\>, I typed the change directory command (cd), then the entire path to the “create” file:

cd D:\PhoneGap\phonegap-phonegap-2.2.0-0-g8a3aa47\phonegap-phonegap-8a3aa47\lib\android\bin

5. Then I followed the steps to create the project with:

create D:\Android\newProject com.stevehusting.newProject newProject

6. I got the following readout from Command Prompt:

Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.

Creating new android project…
Copying template files…
Copying js, jar & config.xml files…
Copying cordova command tools…
Updating AndroidManifest.xml and Main Activity…

D:\PhoneGap\phonegap-phonegap-2.2.0-0-g8a3aa47\phonegap-phonegap-8a3aa47\lib\and
roid\bin>

7. I found all the files set in the location I indicated.

****************
Errors encountered:
****************

a. I received a message from the console after the ./create command when following the instructions online n early Nov. 2012:
‘.’ is not recognized as an internal or external command, operable program or batch file.
Don’t use this command; the error is saying that Windows doesn’t recognize it as a command to follow or program to run. Instead, use the \create.bat command for Windows, as noted above. The error message disappears.

b. I received a message from the console after following my own instructions above:

Missing one of the following:
JDK: http://java.oracle.com
Android SDK: http://developer.android.com
Apache ant: http://ant.apache.org

1. I double-checked my PATH and found I had not put in the Ant path:

;C:\Program Files\adt-bundle-windows\sdk\tools\ant

Still returned same error message. Simon addressed this issue here: http://simonmacdonald.blogspot.ca/2012/11/getting-create-command-to-work-on.html
2. I went to http://ant.apache.org/bindownload.cgi and downloaded the zip archive apache-ant-1.8.4-bin.zip (7.67MB).
3. I extracted the file to C:\Program Files\apache-ant-1.8.4-bin
I replaced the previous Ant path with this one. I had the wrong address for the Ant! I neglected to extend the path to the /bin folder. Reset the Ant variable as: C:\Program Files\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin
As you can see, the full path to the bin folder ends like the original file name: bin. That’s what threw me off.
4. I ran the script in the command prompt and got a new error message:

D:\PhoneGap\phonegap-phonegap-2.2.0-0-g8a3aa47\phonegap-phonegap-8a3aa47\lib\android\bin\create.js(38, 5) Microsoft JScript runtime error: ‘length’ is null or not an object

That’s because I did not write the create command properly. It needs to be written as in my post above.

c. I had problems getting Ant to respond to the command prompt for its version.  I had earlier extracted the compressed file. This time I opened the compressed file and dragged the folder to C:/Programs Files and got a different folder system and the /bin folder in which the elusive ant.bat resided. Then I removed the ANT_HOME listing from the Environment Variables top box and replaced the old address with the new one (C:\Program Files\apache-ant-1.8.4\bin) and updated this post. Now the command prompt responds with the version when I type ant -version.

****************
END Errors encountered
****************

Set Up Project in Eclipse

1. Start up Eclipse.
2. Project > New > Project
3. Click on the + button to the left of Android to show its folder.
4. Choose Android Project from Existing Code, and hit Next.
5. Click on the Browser button and select the folder you used for <project_folder_path>. Mine was D:\Android\newProject
6. If you have a workspace already, check Copy projects into workspace; otherwise, leave it unchecked. Mine was left unchecked.
7. Hit Finish and wait.
8. The project has a ! warning: “The import android.app.Activity is never used.”

Warning Encountered

1. Regarding warning at step 8. To resolve, navigate in the Package Explorer at left through src > com.<project info> > newProject.java, right-click on the latter, and choose Open with > Text Editor.
2. Change the following to comment out the line:

import android.app.Activity;

to . . .

/* import android.app.Activity; */

3. Project > Clean should make the warning go away.

Choose an Onscreen Emulator (Virtual Device)

1. In Eclipse: Window > Android Virtual Device Manager.
2. Click on New…
4. Click on Device and choose one.
5. To help you remember the device, enter its name in the AVD Name field, no spaces.
6. Choose the target level or accept the default.
7. Choose the CPU/ABI. (I received an error in the console when deploying: “Failed to allocate memory: 8. This application has requested the Runtime to terminate it in an unusual way.” I changed the CPU/ABI’s arm7 to MiPs and that solved it.)
8. Type in the Internal Storage available and other fields, and hit OK. When the next window appears, hit Refresh, then exit.

9. Copy all your program’s files into the www/ folder. Make sure that the Cordova js file is being properly referenced between the <head></head> tags in the index.html file, like:

<script src=”cordova-2.2.0.js”></script>

10. Replace PhoneGap’s icons and splash screens in assets/www/res/icon and res/screen with your own image files of the same name and dimensions.

Deploy to Virtual Device

1. Right click the project name at left in Eclipse and go to Run As > Android Application.
2. You should see a black screen with “Android” in the center. Move it out of the way so you can still see the Eclipse console. Wait a LONG while (5-30 minutes) as the emulator starts up.
3. When it starts up, the Eclipse console should report the progress.

Deploy to Device

1. Check with your device as to how to install the apk file. (Creation of the apk file, which is uploaded to Google Play as the program people download to their devices,  is detailed later in this article under “Final Steps.”) In my eLocity tablet, it’s a simple matter of copying the apk file to the SD card, navigating to the card in Settings, and selecting the file and choosing to install it. The Google/Asus Nexus 7 does not include an SD card. I downloaded DropBox.com software to the computer and the DropBox app to the Nexus. Once I signed up for an account, I copied the apk file to the computer’s DropBox, then it was accessible on the Nexus. Then I tapped on the file and it asked if I wanted to install. Simple.

2. Once installed, you should see it on the home screen. Check the title underneath to make sure it is not truncated.
3. Tap the icon and check out your work.
4. Make changes to the files as necessary.
5. When you are satisfied, open the project in Eclipse, do a restore (F5), and make your final apk file for upload to your favorite app store.

Error Encountered

When I rotated the physical device to landscape orientation, the app crashed. I fixed it when I added the following line just above </activity> in the AndroidManifest.xml file:

android:configChanges=”keyboardHidden|orientation|screenLayout”

Now when it is rotated, it goes black, then comes on again in the new layout.

Debugging: LogCat to the Rescue

If you are still having problems, like your app simply crashes in the device, you may want to go online and post your problem. You may be told, “What does your adb logcat say?” Be ready to give it to them with these steps.

1. Hook up your device to the computer.
2. Prepare your device for debugging by going to Settings > Developer Options (or similar) and turning on USB Debugging and Allow Mock Locations.
3. Right-click on your app name in Eclipse and choose Run As > Android Application. Your application starts to load onto your device. Quickly go to the next step.
4. Window > Open Perspective > DDMS. You should see your device listed under Devices. You’ll see DDMS at bottom left and LogCat at the bottom right. There are your LogCat entries. You should see a drop-down for various filters, such as verbose and error. Choose Verbose. When you app hangs, then drag from the top to the bottom in that field so it’s all highlighted.
5. Click on the 3.5″ floppy drive Save icon (remember those?) to save to a text file. Copy and paste those contents into the forum when they ask for the adb logcat.

Another source for discovering problems: Window > Show View > Debug. Check the Problems tab. This finds the source of your HTML problems, giving filename, nature of problem, and line number of its location in the file – of all the HTML files in the app. (Through this I discovered a misplaced <h3></h3> in many of my pages that I had overlooked.)

Final Steps

1. In Eclipse, right-click on AndroidManifest.xml and select Open With > Text Editor.
2. Remove all the permissions your app doesn’t need. To learn more about permissions, see:
http://developer.android.com/guide/topics/manifest/uses-feature-element.html
http://developer.android.com/guide/topics/manifest/uses-permission-element.html
http://developer.android.com/reference/android/Manifest.permission.html

3. Explanatory notes on this page:

android:versionCode=”1″
This is the first version of your app. Subsequent versions are always sequentially numbered. Not shown to the public.

android:versionName=”1.0″>
This is the actual version shown to users.

Below this is the <uses-sdk> section. For the minSdkVersion, put the lowest version your app is designed to use, such as “8? for Android 2.2. For the targetSdkVersion, put the number for the highest device you’ve tested it against (my current “Jelly Bean” device would be “15?). If you see a maxSdkVersion, it’s recommended that you leave it blank (according to http://developer.android.com/guide/topics/manifest/uses-sdk-element.html).

(If you started clicking around in Eclipse like I did, you may lose the Project Explorer window. Just go to Window > Show View > Project Explorer to bring it back.)

4. Go to this page and follow the steps from “Add Your Project’s Assets”
https://iphonedevlog.wordpress.com/2012/11/11/cordova-2-2-android-app-creation-in-mountain-lion-with-eclipse-from-install-to-google-play/

5. I experienced a problem when doing a test run in the emulator. Running the emulator, the console says it can’t install, and the emulator remains a black screen. Final console output in Eclipse:

[2012-11-21 09:18:34 – newProject] Uploading newProject.apk onto device ’emulator-5554′
[2012-11-21 09:18:37 – newProject] Installing newProject.apk…
[2012-11-21 09:20:44 – newProject] Failed to install newProject.apk on device ’emulator-5554!
[2012-11-21 09:20:44 – newProject] (null)
[2012-11-21 09:20:45 – newProject] Launch canceled!

1. In Eclipse, click on the checkbox icon right under the menu bar at top to run Android Lint. The Android Lint console reports problems. One problem was that the “uses-sdk” line was in the wrong place.
2. I opened up AndroidManifest.xml and moved this line to just above <supports-screens:

<uses-sdk android:minSdkVersion=”7″ android:targetSdkVersion=”17″/>

After this, the app launched successfully, and the Cordova icon appeared on the screen.

If you have been clicking around the Eclipse environment and lost the project file listing at left (as I did, sigh), then this will get it back. go to Window > Open Perspective > Other… > Resource > OK. This puts the Project Explorer window back in place. 

Preparing for Google Play Launch

Go to this page and scroll down to “Prepare Promotional Artwork” to get the detailed info on preparing for Google Play in my earlier article.

22 thoughts on “Building a PhoneGap Android App in Windows: Cordova 2.2.0 with Eclipse 4.2.1

  1. I got one more issue: The create command worked fine when using C:\project-name or C:\Users\username\Documents\project-name but it didn’t work if my workspace was located in Program files. I don’t know if the problem was that “Program Files” contain a blank or if the UAC doesn’t let you create paths in Program files. I got it working by changing create.bat and create.js a little:

    1) In create.bat I deleted the \ in line 24, because %~dp0 contains the ending \ already.

    2) In create.js I added a function GeneratePath(pFolderPath) which makes sure that all folders in the path that don’t exist, will be created and replaced each call of fso.CreateFolder with the GeneratePath function


    function GeneratePath(pFolderPath) {
    var retval = false;
    if(!fso.FolderExists(pFolderPath)) {
    var path = pFolderPath.split("\\");
    if(path.length>1) {
    var joinedPath = path[0];
    for(var i=1; i<path.length-1; i++)
    joinedPath = joinedPath.concat("\\",path[i]);
    if(GeneratePath(joinedPath)) {
    retval = true;
    fso.CreateFolder(pFolderPath);
    }
    } else if(path.length==1 && path[0].charAt(path[0].length-1)==":") {
    retval = true;
    fso.CreateFolder(pFolderPath);
    }
    } else {
    retval = true;
    }
    return retval;
    }

    3) I changed the exec calls for the copying in lines 170-205 and made sure that the two arguments of the xcopy or copy command are wrapped with double quotes.

    From:

    exec('%comspec% /c xcopy "'+ ROOT + '"\\bin\\templates\\project\\res '+PROJECT_PATH+'\\res\\ /E /Y');

    To:

    exec('%comspec% /c xcopy "'+ ROOT + '\\bin\\templates\\project\\res" "'+PROJECT_PATH+'\\res\\" /E /Y');

    4) I added an additional line to generate the src-path in line 174:

    GeneratePath(ACTIVITY_PATH.split("\\"+ACTIVITY+".java")[0]);

    • Hello, for me everything works individually :
      java
      javac
      adb
      android

      But when I want to create a project there is an error:

      “Missing of the following…”
      I really don’t understand

  2. I use Android API level 17 and deviceready event fails to fire. I read somewhere that this is a bug in cordova 2.2.0. In your post, are you using level 17 API? How do you make it work?

    Thanks.

  3. i cant install ant 1.8.4 on windows machine 64 bit with jdk 1.7 and
    this message appear
    C:\Users\vie>ant
    Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre7\li
    b\tools.jar
    Buildfile: build.xml does not exist!
    Build failed

  4. I created a new Android project, with success, according to the command prompt. But now I can’t find the project in the location I indicated. And when I run the ‘create’ command again, it says: “Project already exists!”. How is this possible?

  5. 7. I found all the files set in the location I indicated.

    I am working with phonegap 2.6 create command is working but i dont find all files at place.
    I have to copy files manually.

    What can be wrong?

  6. Pingback: Phonegap com Eclipse: programação Android no Windows | Frederico Marinho

  7. Pingback: Cordova PhoneGap 2.7.0 in Windows with Eclipse | iPhone Dev Log

  8. Pingback: Wich mobile development open source Framework should I use? [closed] | Some Cordova Questions and Answers

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.