November 5, 2014

[Tutorial] HTML5 Mobile App Setup Tutorial

Note: This tutorial was written a couple years ago now, and is likely obsolete in a lot of ways. Still, it may be helpful, so give it a look-see if it's relevant to you.





This post is mostly for my own reference, but maybe it'll help others. I'm going to run through the steps to set up an HTML5 project from scratch, building for the Android platform, utilizing the software listed below. I realize there are all-in-one packages for these out there, but I feel it's important to understand the individual parts and how they work together before having it all handed to you. That being said, if anyone has suggestions on something better to use, or if the links are broken, please let me know in the comments!

Note: This is a work in progress, and I might go back and add things to the post, so you may want to check back here periodically. Any information that changes may require a new post to be written, and I'll link to the new post if necessary.

  • Git - Revision control system for maintaining project files.
  • Sublime Text - Enhanced text editor.
  • Cordova - API that allows HTML5 projects to access mobile platform features such as the accelerometer.
  • Android SDK - Used for compiling and testing on Android devices. Comes with Eclipse.
  • Bootstrap - A responsive web page framework.
  • jQuery - A Javascript library that makes Javascript suck a lot less.
  • AngularJS - A Javascript-based templating framework that we'll be using for MVC.
  • ngStorage - A plugin for accessing the browser's localstorage through AngularJS.
  • SimpLESS - A compiler for LESS.

Getting Started

First, of course, you'll want to download all of the software listed above. Setup will be covered in each section following this one, though they're mostly self-explanatory as far as installation goes. You'll want to follow this guide in the order I have things, as it does make things easier. Please note that this guide assumes you are on a computer running at least Windows 7.

Git

We'll install Git first, as it doesn't require any of the other stuff be installed first, but there will be things that rely on it. Before anything else, you'll need to go to GitHub and set up an account. Then you can download Git (as linked above) and install it. If you're new to Git, even if you have experience with version control systems, I recommend reading through the Git Basics.

Git uses a command line interface for everything, so be prepared to do a lot of typing. Open up the Git Bash, and enter these commands, replacing "Name" and "email@email.com" as needed.

git config --global user.name "Name"
git config --global user.email "email@email.com"

These commands have registered your name and email with Git. Whenever you commit a change, your name and email will be added to the log along with what changed and when. This is important for when you're working in teams with other people, and they may be modifying some of the same files you're working on. That's all we need from Git for now.

Android SDK

You're going to need Java before doing this. More specifically, you're going to need a Java Development Kit (JDK) rather than the more typical Java Runtime Environment (JRE). At the time of this writing, the latest version of Java is 8, so you can grab the Java SE Development Kit, making sure to install the 64-bit version in addition to the 32-bit version if your version of Windows supports it.

Once Java is installed, open the Android SDK ZIP file and extract it to wherever you'd like (I typically put everything in "C:\Program Files\Android SDK\"). Then run "SDK Manager.exe" and install any updates it needs. You may also need to install additional files depending on what versions of Android you're targeting. Close that once it's finished. Then you'll need to add a path variable to the SDK.

To do this, go to the Control Panel and open System. Click the "Advanced System Settings" link on the left, and then click the "Environment Variables" button. Below the System Variables section, click "New...". In the name field, type "ANDROID_HOME" without the quotes, and in the value field, type in "C:\Program Files\Android SDK\sdk" without quotes. Hit OK, then in the System Variables box, select the PATH variable and click the "Edit..." button. At the end of the value field, add this text, including the semicolon at the beginning:

;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools

Ant

Download the latest binary for Ant, which should give you a ZIP file. Extract the contents wherever you'd like Ant to be installed. Then go back to where you were adding PATH variables before. Click the "New..." button, name the variable ANT_HOME, and put in the location of the Ant folder you extracted. Then edit the PATH variable, and add this text (again including the semicolon at the beginning):

;%ANT_HOME%/bin

There's really only one reason we need Ant for this tutorial, but it may also come in handy later.

Cordova

You're going to need to install Node.JS before installing Cordova. Unfortunately, tutorials on installing Cordova without Node are more rare than Bigfoot, but the upside is since everyone is doing it, there's plenty of documentation on how. So download and install that first.

Now open the Node.JS command prompt, called the CLI (command line interface). Enter this command:

npm install -g cordova

Once that's done, still in the CLI, browse to the folder that will contain your project. Then enter this command:

cordova create ProjectName com.yourname.projectname ProjectName

This will download and set up all of the files you'll need for Cordova. The first "ProjectName" in the line (which is, of course, the name of your project) will be the name of the folder that Cordova creates for you and places the project files in. The next line is a reverse domain-style identifier, and the third is a title for your project. If you'd like, you could use a string for the title instead, such as "This is ProjectName" (with the quotes).

Next we need to install the platforms we want to compile to. I'm only interested in Android and iOS, so I'll be using these commands:

cd ProjectName
cordova platform add android

And that is it for getting Cordova set up via Node.JS. If you poke around in the project folder now, you should see a "platforms" folder and a "www" folder. "platforms" should contain an "android" folder, and it's here that your project compiles to through Cordova. Your working directory is inside the "www" folder, so adding and editing files will happen in here. Now we need to get it to compile through Eclipse, which comes with the Android SDK.

Eclipse

Eclipse comes with the Android SDK, along with a few Android-related plugins. You can find it in the same folder as Android's "sdk" folder. Open Eclipse, and go to File > New > Project. Expand the Android folder, choose "Android Project from Existing Code", and click Next. For the "root directory" field, browse to your project's "android" folder, and select it. Then hit finish.

When it's done setting up, we'll need to grab the latest Cordova JAR file, as it doesn't come with Cordova but needs to be compiled. Open the Git Bash command line and browse to the folder you put your projects in (not ProjectName but the folder above it). Then clone down the repository for Cordova:

git clone https://github.com/apache/cordova-android

When that's done, browse into the "cordova-android" folder, and then into the "framework" folder. Then enter these commands to compile the JAR:

android update project -p . -t android-19
ant jar

Now copy the generated JAR file, go to your project folder, and then into "...\platforms\android\libs" and paste the file. Then go back into Eclipse, right-click on the project's name in the Package Explorer, and go to Properties, select "Resource", and then "Resource Filters". Click Add, select "Exclude All", select "Files and Folders", and check "All children". In the text field next to the dropdowns for "Name" and "Matches", type in ".git". This will prevent our Git meta files, which are considered extensionless, from interfering with the compiler later (an unfortunately common bug). Click OK, and OK again, then File > Restart. When it's finished loading up again, go to Project > Clean.

If you get any errors about "multiple dex files", here's what you'll need to do: First, try deleting the cordova-android JAR file from the "libs" folder, then clean and rebuild. Second, right-click on your project in Eclipse, go to Properties > Java Build Path > Order and Export, and deselect any of the Android options. Hit OK, restart Eclipse, then clean, build and run.

Eclipse should now be good to go. If you want to test how Eclipse compiles and runs apps, plug in your phone. Make sure all of your drivers and everything are set up (something I won't cover here, as it's dependent on your phone, it's OS version, and other details). Then go to Run > Run. It should prompt you with a list of connected devices, which will likely only include your phone. Select it, and click OK.

Note: When you make changes to the files in your "www" folder, you will need to recompile the app through Cordova before building in Eclipse and pushing it to your phone. Let's say you modified "index.html"; you'll need to go into the Node command line and enter this command from your project's folder:

cordova build android

When that's finished, go back into Eclipse and do a clean, followed by a build. Then you can run the app on your phone again.

Sublime Text

Sublime Text is an easy to use text editor that supports syntax highlighting, project management, and other features. It's very helpful for making changes in the front-end files that don't require editing or compiling through Eclipse. Once you have it installed and open, go to File > Open Folder. Browse to your project folder, then the "www" folder, and open it. This will create a project view for all of your files. Now go to Project > Save Project As. Give this project file a name (probably the same name as your project) and save it in this folder.

Bootstrap

Bootstrap is an HTML5 framework built with a "mobile first" philosophy, and is designed to be responsive. Open the archive that contains Bootstrap, and you should have three folders: "css", "fonts", and "js". Copy these folders into your project's "www" folder.

SimpLESS

Next you will need a main CSS file. Rather than create one or use the "index.css" file that was generated by Cordova, however, we're going to do something a little different. Go into the "css" folder, create a new text document, and rename it to "main.less". Open this file in Sublime Text, and add this code.

body {
  background-color: #fff;
}

Save the file. At this point, make sure you have SimpLESS installed. Once it is, open it, and it will ask you to drag and drop your project folder onto the window. Do so, and it should list the main.less file, and will likely say "not compiled" on the right side. Toward the upper left corner of the window, next to where it says "main.less" in bold, you'll see a refresh button (two arrows in a circle). Click that, and it will compile the LESS file into a main.css file. You will NOT be editing the CSS file! Rather, you will make your edits in the LESS file, using that language, and compiling with SimpLESS. You'll need to read up on how LESS works if you're not familiar with it, of course, but I'm sure you'll find it to be much easier to use than CSS.

jQuery

You will likely want to grab both the minified (condensed) and source versions of the latest version. Later, you can decide which to keep (most developers just use the minified one). Take these files and copy them into "YourProject/www/js". Create another text document in this "js" folder, and rename it to "main.js". Open the file in Sublime Text and paste this code inside it, and then save it.

function() {
    //stuff goes here
}

index.html

In Sublime Text, open the "index.html" file in the "www" folder. It should currently only contain what was generated by Cordova when we first set that up. I'm going to paste in my copy of the file below, and I'll highlight certain lines that I've added and tell you what they are for.

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <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/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <link rel="stylesheet" type="text/css" href="css/main.css" />
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
            </div>
        </div>

        <!--DO NOT PUT HTML BELOW THIS LINE-->
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
        <script type="text/javascript" src="js/bootstrap.min.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
        <script type="text/javascript" src="js/main.js"></script>
    </body>
</html>

The blue lines are includes for CSS and Javascript files, necessary if you want to actually use them. The orange lines are text that can be removed or modified however you'd like.

AngularJS and ngStorage

Coming soon (and thus omitted from the next section for now), though you have everything you need to get started with building a web app. In the meantime, here's a very nice, quick tutorial on how to set up Angular and how it works.

Local Browser Testing

It may be helpful to test the project in a local browser on your computer before pushing it to your Android device. To do that, we need to install a couple more modules through Node. In the Node terminal, browse into your project folder, and run these commands:

npm install -g connect
npm install connect
npm install serve-static

Then in Sublime Text, open a new file, and copy/paste this into it:

var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);

Save the file as "server.js" into the root of your project folder. Then back in the Node terminal, run this command:

node server.js

It should start a server. Now open your preferred web browser and go to this address:

http://localhost:8080/www/

You should now see the project in your browser. This is helpful for HTML development, but you'll be missing some of the Android integration features that Cordova gives you. For that, you'll want to set up remote debugging in Chrome.

Git (Project Backup)

Now we can add this project to Git. Type in "cd", a space, and then start typing the directory path that contains your project folder; i.e., "C:\Projects". Hit enter, and Git should show you in that location. Enter in "ls" and it will list all of the files and folders in that location, which should include your project folder. To add the project to Git, we need a few more commands. First, initialize the folder:

git init YourProjectFolder

Then go inside the folder:

cd YourProjectFolder

You can do "ls" again if you'd like to see the contents. There are some things we don't want to back up to Git, as they're generated when you set up the project. To exclude them, we need a ".gitignore" file. In the CLI, enter this command:

touch .gitignore

This will create the file in your project folder. Open that file through Sublime Text, and copy/paste this into it:

# ANDROID / ECLIPSE
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files - android project subfolder
Android/bin/
Android/gen/
Android/assets/
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
# IOS / Xcode
build/*
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
*.xcworkspace
!default.xcworkspace
xcuserdata
profile
*.moved-aside
IOS/www/
# OSX
.DS_Store
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes

The above was pulled from this Phonegap .gitignore that I found through a Stack Overflow page. Save and close the file. Now we need to add the contents to staging, which is where Git tracks changes made locally.

git add .

It's worth noting that instead of using the period in the command above, you can type in a specific file name. Now we need to commit the files, since we are satisfied with our changes and wish to retain them. We'll need to add a comment about what changes we made, in case we need to go back later and revert to an earlier version of our project.

git commit -m "A comment about the files being uploaded."

As we continue to work on the project, we'll need to keep Git updated on our progress. Whenever you want to look for new changes, check the project's status.

git status

If you don't want something to get added to staging, you can do "git rm --cached filename.extension". Otherwise, add and commit them like before:

git add .
git commit -m "Another comment about the changes made."

There are other commands in Git that you'll want to familiarize yourself with. Definitely check out some tutorial videos on YouTube, and print out or save this Git cheat sheet. I'm only going to cover the bare minimum here, as this early in the game I'm only interested in keeping a backup. Later on, you can do more advanced things like "fork" your code, duplicating the project and modifying it in a different way from the master version.

Of course, what good is a backup if it exists on the same drive as the original? GitHub will help us there, providing us with a remote repository. Go there now and create an account if you have not done so already. Now we need a repository to upload to. On the GitHub page, click the plus sign to the right of your username, and click "New Repository". Enter your project name for the url, give it a description, and leave it on "public" (you're probably using a free account, so you can't set it to private anyway). Don't bother with setting up a readme, just create the repository.

On the next page you'll see some Git commands for creating a new repository and adding an existing one. We'll be doing the latter, but there are some things we need to do first. You will need to generate an SSH key so GitHub will grant you access to upload your files. Please follow this guide to do so, as it doesn't get any more clear-cut than that. (If you have an issue with "ssh-add", try running the command eval `ssh-agent -s` first, using the accents on the tilde key.) Once that's done, we can upload our files!

Make sure the Git command line has your current location inside your project folder. Then type in this command, but DO NOT hit enter yet:

git remote add origin "name of your repository on GitHub"

For the name of your repository, you're going to use something different. Go back to GitHub, click on your username to go to your profile, and then click on your repository. You should see a text box with "HTTP" and "SSH" buttons next to it; click the "SSH" button, and copy the text in the text box. Back in the command line, after "git remote add origin", you're going to paste what you just copied, and hit enter.

Finally, we can upload. To do that, we must "push" our code up to the repository, like so:

git push -u origin master

This will send the master version (the version all other version are eventually merged with) of our code up to the repository via the url given under the "origin" parameter. If you refresh the project page on GitHub, you should now see your files there.

Cloning

If you want to work on another computer, you'll need to install Git, enter the global config commands, and generate SSH keys to give to GitHub. Then in the Node command line, run this command:

cordova create projectname com.yourname.projectname ProjectName

Then in the Git command line, browse to the folder above your project folder, and run these commands:

git clone "the SSH address from GitHub" temp
mv temp/.git ProjectName/.git
rm -rf temp

This will clone your remote repository to a new folder, "temp", then move the Git information to your project folder, and delete the "temp" folder. Next you'll want to pull down your remote files to make it up-to-date locally:

cd ProjectName
git fetch --all
git reset --hard origin/master

This will reset the HEAD to be whatever version is in the remote repository, and copy down all of the files, syncing everything up. But we're still missing the build of the Cordova app, so go back into the Node command line and run this command:

cordova platform add android

Then you'll need to generate the JAR file from the "cordova-android" project if you don't have a recent copy of it, and paste it into the "ProjectName/platforms/android/libs" folder as before. Then follow the instructions above to import the project into Eclipse, build the Cordova app through Node, then clean, build, and run the app in Eclipse. That should be it!

Additional Steps

These are miscellaneous things you may want to do for your project. One thing I'd suggest getting in the habit of doing is making any other folders you think you'll need, such as an "img" folder to store your images. You might want to look into things like IonicBower and Gulp to make project setup and management easier. I'll likely be learning these later on, and might do a tutorial on setting them up. But for now, I guess that's it!

Closing Thoughts

That's the end of this tutorial. "Now what?" you may be thinking. Well don't look at me, this is mostly for my own reference! In all seriousness, I do hope this guide has been helpful in some way. The technologies I've used here are pretty standard for Android web app development, so you'll likely find plenty of other resources to help you from here, such as communities on Google+ or Stack Overflow. As Ms. Frizzle would say, "Get Messy! Make mistakes!"

No comments:

Post a Comment