Saturday, December 31, 2011

On the Seventh Day of PhoneGapping: Debugging

One of the truly horrible things about doing web application development on mobile phones is the lack of web development tools that you'd see in modern desktop web browsers. Luckily for us a couple of folks have made it a lot easier to do web dev with tools like weinre by Patrick Mueller and iWebInspector by Maximiliano Firtman. I'm going to spend my time talking about weinre not because iWebInspector isn't as good but because I spend most of my time in Android land so I'm much more familiar with weinre.

The description from the home page:

"weinre is a debugger for web pages, like FireBug (for FireFox) and Web Inspector (for WebKit-based browsers), except it's designed to work remotely, and in particular, to allow you debug web pages on a mobile device such as a phone."

Isn't that great? You can have the developer tools you are used to back in your greedy little hands again.

The weinre home page has detailed instructions on how to setup your own server, which is not that difficult, but if you are like me (i.e. lazy) there is already a server setup for you at where getting started is only three steps away. 

Friday, December 30, 2011

On the Sixth Day of PhoneGapping: Downloading a File

Did you know that the FileTransfer object got a new download method in PhoneGap 1.3.0? You didn't, well thanks to Alexander Heinrich for spurring it's  development and getting it checked in for Android and iOS (download is also available to you BlackBerry users). Finally PhoneGap developers have a convenient way to download binary files.

The method signature is:
download(source, destination, successCallback, errorCallback);
Where the parameters are:

source: The URL you want to download
destination: The full file path you want the file stored at
successCallback: called with a FileEntry object that represents the new file
errorCallback: called when something goes wrong

So say we want to download a PNG image and store it on the SD card. Well you'd write some code that looks like this:

Thursday, December 29, 2011

On the Fifth Day of PhoneGapping: Five Two Minute Tutorials

Another re-blog but there are some gems here as the folks at Mobile Development Solutions have put together 5 two minute tutorials using PhoneGap Android.

They've put together tutorials on:

1) Media Player
2) Getting your app market ready
3) Barcode Scanning
4) Google Maps
5) Twitter and OAuth

Thanks to Libby and Paul for everything they do to support the PhoneGap community.

Wednesday, December 28, 2011

On the Fourth Day of PhoneGapping: Creating a Database from a SQL Dump

On a slightly different track than Day 2 we are going to create a SQLiteDB from scratch using only JavaScript on startup of our application. In order to do this we are going to use the handy JavaScript library HTML5SQL.js by Ken Corbett Jr.

First we'll do a check to see if we've already created our database. If we haven't we'll do a XHR to get the SQL dump file containing all the statements we need to create and populate our tables. Finally, upon success we'll set a flag so this doesn't run every time we start our application.

and here is our sql file:

The html5sql.js lib makes working with the Web SQL specification much easier than hard coding it yourself. You owe it to yourself to look into this library as it will save you some time and hair.

Tuesday, December 27, 2011

On the Third Day of PhoneGapping: Getting Data from a Server

Well your application would be pretty useless if you couldn't get data from a remote server now wouldn't it? Luckily since your PhoneGap application is running off of the file:// protocol it isn't limited by the same origin policy. This means we can request data using XmlHttpRequest from any domain.

I'm going to give you an example of searching for all tweets that mention PhoneGap that demonstrates this ability without the use of any extra JavaScript library like jQuery or Dojo.

So that is the example in a nutshell. It isn't very different from your normal XHR call except for one line that I need to bring to your attention:
if (request.status == 200 || request.status == 0) {
Most of the time you are just looking for the 200 status code you also need to accept the status code of 0 as also OK. Sometimes when you are requesting data via XHR from the file:// protocol you will get a 0 status code. As I said that is perfectly normal and you should treat it as a 200 and move on with your application.

Much of the rest of this code is just building up a HTML string I can do an insert into a div I've set aside for displaying the tweets. Just wanted to show everyone how easy it is to communicate with a remote server.

Monday, December 26, 2011

On the Second Day of PhoneGapping: Copying a native database

The topic of creating a large SQLiteDB to persist data on the device comes up a lot on the Google Group. Sadly, most of the modern web browsers limit you to a maximum database size of 5 megabytes. If you really need a database bigger than that you'll need to jump through a few hoops.

Luckily a developer by the name of Gaurav S Tomar has already gone through the process of explaining how to do this in his excellent blog post:

Prepopulate SQLite DataBase in PhoneGap Application

So go check it out!

What you say? Here we are on the second day and he's already pointing us to other people's blog posts. Well I never said I was going to write the all just want to make you aware of some tricks you can use in your PhoneGap applications.

Sunday, December 25, 2011

On the First Day of PhoneGapping: Get to deviceready faster on Android

This tip is courtesy of a question that Pamela Fox posted up over on the PhoneGap Google Group as she was wondering why it sometimes takes longer for the PhoneGap deviceready event to fire.

As all good PhoneGappers know you need to wait until you receive the deviceready event before you can call any of the PhoneGap API's. But, what has to happen before the deviceready event fires? Well here is breakdown of events that fire before deviceready:

  1. onDOMContentLoaded Internal event that is received when the web page is loaded and parsed.
  2. window.onload Body onload event.
  3. onNativeReady Internal event that indicates the PhoneGap native side is ready.
  4. onPhoneGapInit Internal event that kicks off creation of all PhoneGap JavaScript objects (runs constructors).
  5. onPhoneGapReady Internal event fired when all PhoneGap JavaScript objects have been created
  6. onPhoneGapInfoReady Internal event fired when device properties are available
  7. onPhoneGapConnectionReady Internal event fired when the connection property has been set.
  8. onDeviceReady User event fired to indicate that PhoneGap is ready
That may seem like a lot but you don't have to worry about it as you can't speed up the process any. That is, except in one area. The onNativeReady event does not fire until the the onPageFinished method gets called on the Android WebViewClient.

So anything you do that increases the amount of time before the web view understands the page is completely loaded will keep you from getting to deviceready. For instance if you are doing a lot of things  in the window.onload method it will delay deviceready. In Pamela's particular instance she was doing an XmlHttpRequest in the onload method which delayed things.

The fix and the tip in this case is to move as many things from your onload event handler to your deviceready event handler.

Friday, December 23, 2011

Books I've Read This Week

I still haven't finished The Children of the Sky but here are some awfully short reviews to tie you over.

B.P.R.D. Volume 10: The Warning Liz is kidnapped and it is up to the team to track down the creepy guy who took her. In the background the teams main enemies get together and get organized.

B.P.R.D. Volume 11: The Black Goddess the team successfully tracks down Liz but will they be able to save her against the Frogs, the Black Flame and the remnants of Hyperborea. Plus, I'm really really beginning to hate Johann.

X-Factor, Vol. 1: The Longest Night by Peter David is a book I've been meaning to read for awhile now. I like this hard boiled detective story set in the Marvel Universe where the detectives are all mutants with super powers. I really enjoyed the first volume and I'm looking forward to the second.

See you next Friday.

Twelve Days of PhoneGapping!

Starting on Christmas Day, December 25th, I'll be posting one PhoneGap tip per day for 12 days in what I'm grandiosely calling The Twelve Days of PhoneGap. Some of these tips you'll already know and some you won't but hopefully we'll all learn something.

For most of those days I'll actually be on vacation so it may take a bit for me to respond to any comments left on the post. Here's hoping everyone has a great holiday season!

Friday, December 16, 2011

Books I've Read This Week

I know I hinted at a review for The Children of the Sky but I haven't finished with it yet so you'll have to be happy with:

Naruto, Vol. 52 is the last volume I'll be reading for awhile as I've completely caught up on the series with volume 53 just being released on Dec 6th and my local library does not have it yet. We get the beginnings of a battle between Naruto and Sasuke who were once best of friends but now are mortal enemies as Sasuke has been led down a dark path. Stop me if you've heard this one before. Anyway, I don't want to be flippant but you can see how Naruto is maturing so much so I'm beginning to like him more. Funny that the title's main character was not always your favourite character.

Morning Glories, Vol. 2 by Nick Spencer is like the movie The Breakfast Club mixed with a horror movie that's on crack. In the first volume we are introduced the the school, Morning Glory Academy but we don't really get to know a lot about the 6 kids that are the main characters as they are struggling to fit in and well not be killed by the school and the creepy faculty. Now in volume 2 we are treated to 6 individual stories each one focusing on a main character. We get to see there is more depth behind, the rich kid, the jock, the smart one, the geek, the cheerleader and the goth in a number of surprising ways. All the while Spencer is able to move the story forward while giving valuable background information.

Also, the series artist Joe Eisma is absolutely killing it and you should check this recent breakdown of his art on the series.

See you next Friday.

Friday, December 9, 2011

Books I've Read This Week

Nothing to report this week. My daughter was sick for about five days with a fever/flu which cut into my reading time. I'm just cracking open The Children of the Sky by Vernor Vinge which promisses to be a great read.

See you next Friday.

Friday, December 2, 2011

Installing the Barcode Plugin for PhoneGap Android

Some folks are having problems getting the Barcode Scanner plugin up and running for PhoneGap Android so I figured I'd write a more detailed explanation on how to get it up and running.

First you'll want to go download the Library Project part from GitHub. You'll want to use the code from github as I've modified it slightly so that it is responds to the correct intent.

Once downloaded you'll want to create a new Android project from existing source in Eclipse. The project name shows up as CaptureActivity but I'm going to change it to BarcodeLibrary which is more descriptive.

but don't click on Finish yet. Click the Next button...

and select the highest level of Android SDK you have installed before clicking Finish.

Now that you've created the library project which contains the barcode scanning code you'll want to right mouse click on the BarcodeLibrary project and select Properties. In the Properties dialog, select the Android tab and ensure the Is Library checkbox is click. The benefit of doing things this way is you can link this library into multiple Android projects without needing to copy a bunch of source around.

Now that we've got our library setup let's add it to our project. Right click on your PhoneGap project, in my case it is called BarTest, and select Properties.

In the Android tab under the library section click the Add button.

In the Project Selection dialog select BarcodeLibrary.

Now our application can use the BarcodeLibrary project so we can click OK.

Let's now add in the BarcodeScanning plugin code. Under the assets/www directory copy in the barcodescanner.js file from github. Under src, right click and create a new package com.phonegap.plugins.barcodescanner then copy in the file from github.

So were all set now right? Well know we forgot one thing. We need to add a line for our plugin under the res/xml/plugins.xml file so let's open that up now and add this line after the last <plugin/> tag but before the </plugins> line.

<plugin name="BarcodeScanner" value="com.phonegap.plugins.barcodescanner.BarcodeScanner"/>

Okay, so were good now. Well no, there is one more bit to take care of. Open up your AndroidManifest.xml file so we can add some new activities that will take care of the scanning and encoding. You'll need to paste these activity lines inside the <application/> tag.

<activity android:name=""
    <action android:name="com.phonegap.plugins.barcodescanner.SCAN"/>
    <category android:name="android.intent.category.DEFAULT"/>
<activity android:name="" 
    <action android:name="com.phonegap.plugins.barcodescanner.ENCODE"/>
    <category android:name="android.intent.category.DEFAULT"/>
Update: With later versions of PhoneGap the CAMERA permission was removed as it was not required. However, for the barcode scanner it is. So add the following permissions line:

<uses-permission android:name="android.permission.CAMERA" />

Alright, finally we are all setup. But how does one call the BarcodeScanner? Well we provide two main piece of functionality.

window.plugins.barcodeScanner.scan( function(result) {
        alert("We got a barcode\n" +
                  "Result: " + result.text + "\n" +
                  "Format: " + result.format + "\n" +
                  "Cancelled: " + result.cancelled);
    }, function(error) {
        alert("Scanning failed: " + error);

window.plugins.barcodeScanner.encode(BarcodeScanner.Encode.TEXT_TYPE, "", function(success) {
        alert("encode success: " + success);
      }, function(fail) {
        alert("encoding failed: " + fail);

I've put together a small example html (and css) page which will be listed below that you can use to test the BarcodeScanner.

If you have problems with the Barcode Scanner the best place to ask questions is over on the PhoneGap Google Group where I check multiple times per day for questions I can answer.

Books I've Read This Week

Programming HTML5 Applications by Zachary Kessin is a good overview of a number of new HTML5 JavaScript API's that are becoming available in your browser. Wherever possible these are the specs we try to follow when implementing the PhoneGap API. It is a relatively short book at 130 pages so you should really look for it on the O'Reilly's Deal of the Day feed.

Snuff by Terry Prachett is another home run by a master storyteller. I wasn't a fan of Sir Prachett when I read his first book The Color of Magic but he really didn't hit his stride as an author until his third or fourth book. Since I didn't like the first book I kinda ignored Discworld for a long time much to my detriment.

Snuff is the 39th novel set in Discworld and it features my favourite character in the series, Commander Sam Vimes of the City Watch. This is a novel about the slavery and racism that Sam Vimes runs into while on vacation. No other author that I know of can tackle such a serious issue with as much humour as Terry Prachett can while at the same time making the reader really think.

Can't recommend Snuff and Prachett's earlier works highly enough.

Rule 34 by Charles Stross is sort of a sequel to his earlier Halting State but luckily you don't need to read the previous book to enjoy this one. This book is more of a police procedural set in a near future where the internet permeates our lives completely. You follow a number of main characters as the detectives try and track down who is killing spammers.

The real joy of this book is Charlie's extrapolation on how the internet will affect our near future society and policing in general. It was a pretty fun and interesting book to read.

See you next Friday.

Thursday, December 1, 2011

Living with Android

I just wanted to give a brief update on how things have been going living with Android full time. Back in September I decided not to re-up my three year contract with Rogers on my iPhone 3G and give Android a month to woo me. The experiment was not without it's tribulations as attempting to upgrade my OS from 2.1 to 2.3 using the Samsung Kies software bricked my phone. Luckily, I was able to resolve that problem by flashing my firmware with ODIN.

Honestly, since that time life with Android has been pretty great. That is until my trip to AnDevCon in San Francisco. While on that trip I noticed my phone was extremely hot which was unusual. Once I took it out of my pocket I saw that it was rebooting to which I assumed I was out of battery but that was not the case. The phone was constantly rebooting loading the Samsung welcome screen and then rebooting again. In order to make it stop I needed to pull the battery out of the back.

Initially I wasn't concerned as I figured it either needed a full charge or worse case scenario I could flash the firmware again using ODIN. Sadly, upon return home to Ottawa nothing I tried to fix the phone would work. The phone would flash to Android 2.3.5 but still it was stuck in the rebooting cycle.

I called Bell Canada from whom we purchased the phone. Since the phone died 1 week after it's 1 year warranty Bell wanted $50 to look at the phone and anywhere between $50 to $200 in order to fix the phone. This really didn't make a lot of sense to me as at that point I might as well buy a new phone.

Thanks to a suggestion by my bosses boss I called Samsung Canada. After about 10-15 minutes on the phone with first and second line support Samsung emailed me a UPS shipping label for me to send the phone into them where they would fix it for free. Oh happy day! Finally, a company that still stands behind their product and provides good customer support.

So I got the phone back after about 2 weeks and it is working good. I've already flashed it to the latest Gingerbread release 2.3.5 and I've never been happier with my Android phone.

However, after using my iPhone for almost a month as just a music player and browser I gotta say it is pretty sweet. I'm going to try to hold off a bit longer but I'm pretty sure there will be an iPhone 5 in my future once that magical new device is releases.