Getting Started with Cordova Applications
This tutorial needs a review. You can edit it in GitHub following these contribution guidelines. |
This document demonstrates how to create an HTML5 project in the IDE that is packaged as a mobile application and run in a mobile device simulator. When you create an HTML5 application you have the option to create the application using an Apache Cordova site template. Apache Cordova provides a group of APIs that enable you to develop an application with HTML, CSS and JavaScript that is packaged as a native mobile application. The application runs on the mobile device and can access the native functions of the device such as the GPS or camera. By using the Cordova APIs a developer can build a mobile application without writing any native code.
This document demonstrates how to install the software that is necessary to install and develop an application with Cordova. After you install Cordova you will use the Cordova template in the New Project wizard to create a Cordova application. You will then add some code and run the application in the mobile device simulator. This tutorial will use the iOS simulator, but the steps are similar if you want to use an Android device emulator.
To watch a screencast that demonstrates deploying a Cordova application to the Android emulator, see Video of Getting Started with Cordova Development.
To complete this tutorial, you will need the following resources.
Software or Resource | Version Required |
---|---|
8.0 |
|
version 7 |
|
— |
|
— |
|
— |
|
Mobile Platform SDK |
Android or iOS |
Notes:
-
This document assumes that a compatible target mobile platform SDK and device emulator is already installed.
-
This document assumes that you have some basic knowledge of, or programming experience with HTML, CSS, and JavaScript. For more details on HTML5 support in NetBeans IDE, see Getting Started with HTML5 Applications
Installing Cordova
You need to install Cordova on your local system to package an HTML5 application as a native mobile application with NetBeans IDE. You will use npm, the NodeJS package manager, to install and to update Cordova. You will also need to confirm that Git is installed on your local system and configured properly. Cordova uses Git to retrieve any required Cordova source files from a repository when you package the application as a native mobile application.
You will perform most of the following steps in this exercise in your terminal window.
-
Download and install Node.js, if not already installed.
You can download the installer from the Node.js site.
-
Open a terminal window.
-
Run the following command to confirm that Node.js is installed.
$ node -v
If node.js is installed you will see a version printed in the terminal window.
Notes.
-
If you are behind a proxy you will need to configure node.js to use the proxy to access the network. You can run the following commands to set the proxy, replacing
http://proxy:8080
with your proxy.
$ sudo npm config set proxy http://proxy:8080
$ sudo npm config set https-proxy http://proxy:8080
You can run the following command to view the current configuration settings.
$ npm config list
-
For additional information about configuring node.js, see https://npmjs.org/doc/config.html.
-
Run the following command to install Cordova.
$ npm install -g cordova
Notes.
-
Confirm that your proxy configuration is correct if you see an error message in the terminal window when you run the install command.
-
You can run the following command to update Cordova to the most recent version.
$ npm update -g cordova
-
Run the following command to confirm that Cordova is installed and to view the version.
$ cordova --version
If Cordova is installed you will see a version printed in the terminal window.
-
Download and install the Git version control system, if not already installed.
You can download the installer from the Git site.
Note. You need to add Git to your Path environment.
-
Run the following command to confirm that Git is installed.
$ git --version
If Git is installed you will see a version printed in the terminal window.
Notes.
-
If you are behind a proxy you will need to configure Git to use the proxy to access the network. You can run the following commands to set the proxy, replacing
http://proxy:8080
with your proxy.
$ git config --global http.proxy http://proxy:8080
$ git config --global https.proxy http://proxy:8080
You can run the following command to view the current configuration settings.
$ git config --list
-
For additional information about configuring Git, see the setup instructions at http://git-scm.com/book/en/Getting-Started-First-Time-Git-Setup.
You now have all the tools that you need to develop and package a native mobile application in the IDE. In the next exercise you will use the New Project wizard to create the application.
Creating a Cordova Application
In this exercise you will use the New Project wizard in the IDE to create a new Cordova application. You create a Cordova application by selecting the Cordova Hello World template as the site template in the New Project wizard. A Cordova application is an HTML5 application with some additional libraries and configuration files. If you have an existing HTML5 application you can use the Project Properties window in the IDE to add the Cordova sources and other files required to package the application as a Cordova application.
For this tutorial you will create a very basic HTML5 project that has an index.html
file and some some JavaScript and CSS files. You will select some jQuery JavaScript libraries when you create the project in the wizard.
-
Select File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) in the main menu to open the New Project wizard.
-
Select the HTML5 category and then select Cordova Application. Click Next.
-
Type CordovaMapApp for the Project Name and specify the directory on your computer where you want to save the project. Click Next.
-
In Step 3. Site Template, confirm that Download Online Template is selected and that the Cordova Hello World template is selected in the list. Click Next.
Note: You must be online to create a project that is based on one of the online templates in the list.
-
In Step 4. JavaScript Files, select the
jquery
andjquery-mobile
JavaScript libraries in the Available pane and click the right-arrow button ( > ) to move the selected libraries to the Selected pane of the wizard. By default the libraries are created in thejs/libraries
folder of the project. For this tutorial you will use the "minified" versions of the JavaScript libraries.
You can use the text field in the panel to filter the list of JavaScript libraries. For example, type jq in the field to help you find the jquery
libraries. You can Ctrl-click the names of the libraries to select multiple libraries.
Notes.
-
You can click on the library version number in the Version column to open a popup window that enables you to select older versions of the library. By default the wizard displays the most recent version.
-
The minimized versions of the JavaScript libraries are compressed versions and the code is not comprehensible when viewed in an editor.
-
In Step 5. Cordova Support, use the default values. Click Finish to complete the wizard.
When you click Finish the IDE creates the project and displays a node for the project in the Projects window and opens the index.html
file in the editor.
If you expand the js/libs
folder in the Projects window you can see that the JavaScript libraries that you specified in the New Project wizard were automatically added to the project. You can remove a JavaScript library from a project by right-clicking the JavaScript file and choosing Delete in the popup menu.
To add a JavaScript library to a project, right-click the project node and choose Properties to open the Project Properties window. You can add libraries in the JavaScript Libraries panel of the Project Properties window. Alternatively, you can copy a JavaScript file that is on your local system directly into the js
folder.
You can now test that your project runs and is deployed to the emulator for your target mobile device.
-
Click the browser select icon in the toolbar and confirm that your target mobile device emulator is selected in the Cordova column in the table. In the Cordova column you can select the Android Emulator or iOS Simulator (requires OS X and XCode).
-
Click the Run icon in the toolbar.
When you choose Run the IDE deploys the Cordova application to the emulator.
Note. If you are deploying to the iOS Simulator the simulator should open automatically. If you are deploying the application to an Android emulator you will need to configure and start the emulator before you run the application. To watch a screencast that demonstrates deploying a Cordova application to the Android emulator, see Video of Getting Started with Cordova Development.
Modifying the Application
In this exercise you will edit the index.html
and index.js
files. You will replace the code generated by the Cordova Hello World template with code to display a map of your current location in the application. You will also modify the default Cordova configuration to remove the Cordova plugins that are not necessary in the application.
Editing the HTML File
In this exercise you edit the HTML file in the source editor to add references to the libraries and CSS files and to add the page elements.
-
Open
index.html
in the editor (if it is not already open).
In the editor you can see that the IDE generated some code based on the Cordova Hello World template.
-
In the editor, add references to the jQuery JavaScript libraries and CSS files that you added when you created the project. Add the following code (in bold) between the opening and closing
<head>
tags.
<html>
<head>
<meta charset=UTF-8">
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
<link rel="stylesheet" type="text/css" href="css/index.css" />
*<link rel="stylesheet" href="js/libs/jquery-mobile/jquery.mobile.min.css"/>
<script type="text/javascript" src="js/libs/jquery/jquery.min.js"></script>
<script type="text/javascript" src="js/libs/jquery-mobile/jquery.mobile.min.js"></script>*
<title>Hello World</title>
</head>
<body>
...
</html>
You can see the path to the files in the Projects window and you can use the code completion in the editor to help you.
-
Add the following link to the Google Maps JavaScript API between the
<head>
tags.
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
Note. This is a link to the deprecated v2 of the JavaScript API. This JavaScript will work for the purpose of demonstration in this tutorial but you should use the newer version in a real application.
-
Remove all the code between the
<body>
tags except for the following links to theindex.js
andcordova.js
JavaScript files.
<body>
*<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>*
</body>
</html>
The index.js
file was generated automatically when you created the project. You can see the file under the js
node in the Projects window. You will modify the code in index.js
later in the tutorial.
The cordova.js
is not visible in the Projects window because it is generated when you build the Cordova application.
-
Add the following code (in bold) between the
body
tags.
<body>
*<div data-dom-cache="false" data-role="page" id="mylocation">
<div data-role="header" data-theme="b">
<h1 id="header">Searching for GPS</h1>
<a data-role="button" class="ui-btn-right" onclick="showAbout()">About</a>
</div>
<div data-role="content" style="padding:0;">
<div id="map" style="width:100%;height:100%; z-index:50">
</div>
</div>
<div data-role="footer" data-theme="b" data-position="fixed" >
<h4>Google Maps</h4>
</div>
</div>
<div data-dom-cache="false" data-role="page" id="about">
<div data-role="header" data-theme="b">
<a data-role="button" data-rel="back" href="#mylocation" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">Back</a>
<h1>About</h1></div>
<div data-role="content" id="aboutContent">
</div>
<div data-role="footer" data-theme="b" data-position="fixed" >
<h4>Created with NetBeans IDE</h4>
</div>
</div>
*
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
Modifying the Cordova Configuration
In this exercise you will modify the list of Cordova plugins that are installed in the application.
-
Right-click the project node in the Projects window and choose Properties in the popup menu.
-
Select Cordova in the list of categories.
You can use the Application tab to view and edit the Cordova configuration details about the application that are specified in config.xml
.
-
Click the Plugins tab in the Cordova panel.
The Plugins tab contains two panes. The Available pane displays a list of the Cordova plugins that are currently available.
The Selected pane displays a list of the plugins that are installed in the application. All plugins are installed by default when you use the Cordova Hello World template to create the application. Most applications do not require all the plugins. You can use the Plugins tab in the Project Properties window to remove the plugins that are not required by your application.
Note. You can also edit the plugins that are installed by editing the nbproject/plugins.properties
file in the editor.
-
Remove all plugins except Device API, Dialogs (Notifications) and Geolocation. Click OK.
Editing the JavaScript File
In this exercise you will remove the JavaScript code generated by the template and add some simple methods to display the map of your current location.
-
Open
index.js
in the editor.
The IDE generated some boilerplate code in index.js
when you created the project. For this application you can remove all the generated code.
-
Replace the generated code with the following code. Save your changes.
var map;
var marker;
var watchID;
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
//uncomment for testing in Chrome browser
// onDeviceReady();
});
function onDeviceReady() {
$(window).unbind();
$(window).bind('pageshow resize orientationchange', function(e) {
max_height();
});
max_height();
google.load("maps", "3.8", {"callback": map, other_params: "sensor=true&language=en"});
}
function max_height() {
var h = $('div[data-role="header"]').outerHeight(true);
var f = $('div[data-role="footer"]').outerHeight(true);
var w = $(window).height();
var c = $('div[data-role="content"]');
var c_h = c.height();
var c_oh = c.outerHeight(true);
var c_new = w - h - f - c_oh + c_h;
var total = h + f + c_oh;
if (c_h < c.get(0).scrollHeight) {
c.height(c.get(0).scrollHeight);
} else {
c.height(c_new);
}
}
function map() {
var latlng = new google.maps.LatLng(50.08, 14.42);
var myOptions = {
zoom: 15,
center: latlng,
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
watchID = navigator.geolocation.watchPosition(gotPosition, null, {maximumAge: 5000, timeout: 60000, enableHighAccuracy: true});
});
}
// Method to open the About dialog
function showAbout() {
showAlert("Google Maps", "Created with NetBeans 7.4");
}
;
function showAlert(message, title) {
if (window.navigator.notification) {
window.navigator.notification.alert(message, null, title, 'OK');
} else {
alert(title ? (title + ": " + message) : message);
}
}
function gotPosition(position) {
map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if (!marker) {
//create marker
marker = new google.maps.Marker({
position: point,
map: map
});
} else {
//move marker to new position
marker.setPosition(point);
}
}
Note. For this tutorial the call to the onDeviceReady
method is commented out because the method is not necessary when you are deploying the application to a mobile device emulator. If you want to run the application in a web browser you should uncomment the call to the onDeviceReady
method.
-
Reset your emulator by either restarting the emulator or resetting the settings.
-
Click Run in the toolbar to deploy the application to the emulator.
On the iOS Simulator you are prompted to allow the application to use your current location.
You can test a simulated location in the iOS Simulator by selecting Debug > Location > Custom Location from the main menu of the iOS Simulator to open the Custom Location dialog box.
If you enter 48.8582 in the Latitude field and 2.2945 in the Longitude field for your current location the application will display your location as the Eiffel Tower on the map.
Debugging the Application
In this exercise you will set a breakpoint in the JavaScript file and run the application again.
-
Reset or relaunch the emulator.
-
Open
index.js
in the editor. -
Place a breakpoint by clicking in the left margin in the following line in the
gotPosition
method.
var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
-
Click Run in the toolbar to run the application again.
When you run the application the debugger will hit the breakpoint when the application tries to determine your current location.
If you hover your cursor over the variables you can see a tooltip that displays details about the variable. If your cursor is over the latitude
variable the value of the variable is displayed in the tooltip.
If your cursor is over position
or coords
the tooltip contains an arrow that you can click to expand the tooltip.
The expanded tooltip enables you to see the values in greater detail.
In this case it is easier to view the values in the Variables window. In the Variables window you can see the latitude and longitude of your current location.
In the Network Monitor window you can see a list of the application requests.
Summary
In this tutorial you have learned how to install and setup the required software to create a Cordova application in the IDE. You also learned how to create a Cordova application and modify some of the Cordova configuration settings.
See Also
For more information about support for HTML5 applications in the IDE on netbeans.org, see the following resources:
-
Working with CSS Style Sheets in HTML5 Applications. A document that continues with the application that you created in this tutorial that demonstrates how to use some of the CSS wizards and windows in the IDE and how to use the Inspect mode in the Chrome browser to visually locate elements in your project sources.
-
Debugging and Testing JavaScript in HTML5 Applications. A document that demonstrates how the IDE provides tools that can help you debug and test JavaScript files in the IDE.
-
Creating JavaScript Files in Developing Applications with NetBeans IDE.
For more information about jQuery, refer to the official documentation:
-
Official Home Page: http://jquery.com
-
UI Home Page: http://jqueryui.com/
-
Tutorials: http://docs.jquery.com/Tutorials
-
Documentation Main Page: http://docs.jquery.com/Main_Page
-
UI Demos and Documentation: http://jqueryui.com/demos/