Category Archives: PhoneGap

Solving “The connection to the server was unsuccessful” Error in Android/PhoneGap

10 Apr 2012

At some point in time you will always have to update your dev environment – and inevitably when doing so you will find that you can’t compile your apps any more for any sort of a number of reasons – doesn’t matter if its iOS or Android (though I find its much, much more common on iOS). Well, today I’ve updated my Android SDK since I’d like for the first time ever to be able to use the AVD as Google has improved performance in that area. However, upon compiling one of my apps I have run into this error:

...
04-10 10:46:13.672: I/System.out(4057): onReceivedError: Error code=-6 Description=The connection to the server was unsuccessful. URL=file:///android_asset/www/index.html
...

This can be solved by adding a line to your main activity.java file:

...
super.setIntegerProperty("loadUrlTimeoutValue", 7000);
...

The timeout value itself is arbitrary, here I have it at 7 seconds. Adding this one line above the super.loadUrl resolves the “Connection to the server was unsuccessful” error.

Also, check to make sure that any remote scripts such as those being delivered to the app from a server are accessible. Sometimes I forget to remove the remote debugger from a project and find that this error will appear because the script cannot be downloaded – in that case you see the error message appear while the app loads behind it. So, check your script tags for remotely loading scripts and remove any hooks to remote debuggers/testing servers. You should also download copies of javascript libraries and keep them within your app to remove or at least reduce the chances of this error appearing.

Prevent PhoneGap UIWebView Bounce in iOS

14 Mar 2012

Here’s a quick one – sometimes your html5 app will for whatever reason cause the UIWebView to break out of PhoneGap’s bounce-less restrictions (for lack of a better way to describe it). This will resolve the issue – in Xcode, look for your AppDelegate.m file, located within the Classes directory. Open that up and look for the function called:

...
 (void)webViewDidFinishLoad:(UIWebView *)theWebView
...

Within the curly braces paste the following line:

...
[[theWebView.subviews objectAtIndex:0] setBounces:NO]; 
...

[edit…]

The ability to control bounce has moved to the config.xml file – there may be multiples of this file within your PhoneGap project so if editing one doesn’t seem to do anything you’ve got the wrong file – do a search for the other one.

Within the config.xml add this node:

Changing Target Android Version in Eclipse

12 Mar 2012

This one takes care of the “Attribute minSdkVersion(x) is lower that the project target API level(x)” error that you may encounter if attmpeting to change your app’s Android target version after having setup your Eclipse project for Phonegap. The error manifests itself as a build error with this the following description (which illustrates a target of 8 being below the projects API level of 10):

To change the target Android API level you need to do two things:

  1. Update the Android Manifest
  2. Update the App Target API Level

See this page for more information on Build Targets and
acceptable values: Android API Level Guide.

First go to your project folder in Eclipse. In the root you should find a file called “AndroidManifest.xml“. Double-click this file. Eclipse will either show you the UI view of the XML document, which looks like this:

Or Eclipse may show you the manifest in source view which would look like this:

In the UI view of the manifest you are looking for the “Min SDK version” filed – set that to the desired SDK version that you want to target. Save the change and then close the manifest. If you cannot locate the Min SDK Version then look under “Manifest Extras” and click on “Uses SDK” – the desired field will appear to the right under the “Attributes for Uses SDK” heading.

If you see the source-code view for the manifest then look for this line:

...

...

… and simply change the number (“8” in the above example) to whichever target API Level that you’re going for.

Next, you need to change the Project Build Target. To do so you will locate the root of your project within the Project Explorer (this appears as a directory tree structure), right click the app project root and select “Properties“. You will see the properties panel which looks like this:

At this point simply select the proper build target, apply and close.

Eclipse Tips for New Users

28 Feb 2012

I don’t know if this is true, but I imagine that the Eclipse user-base is exploding due to the advent of PhoneGap and Mobile Application frameworks like Sencha Touch and JQuery. I’ll go a step further and assume that a significant portion of HTML 5 Mobile App Developers are coming over from the front-end web development world since these new technologies have dropped the entry curve considerably to mobile app development.

So, a lot of new Eclipse users in a new IDE means… (drumroll)… a lot of questions. So in my short time in using Eclipse I’ve come across a handlful of things that I find myself using/doing all of the time that saves time. I thought I’d share these “tips” as you might find them useful as well.

TODO

This is a very handy feature. I find myself starting Sencha Touch projects by first building out the “skeleton” – all the panels, nested panels (the parents of which I personally call “card decks”, as most child panels have the “card” layout), setting up listeners, creating empty functions knowing that I will need to flesh them out at a later date, etc. And so while doing this I need a handy way of indicating that there is something to do in that particular location in my code. Eclipse has a nice visual que for this called “TODO’s” that when used appear in a thin vertical strip next to the vertical scrollbar. This strip is called the “Overview Ruler”. To add a TODO to your project simply create a comment and put the “TODO” text after it (i.e., “/* TODO */” and Eclipse will display a blue marker in the Overview Ruler. Feel free to expound on what needs to be done within your comment as well.

Eclipse also does something that I think is annoying and that interferes with the “TODO” feature – it displays a yellow marker in the same vertical area as it does the blue “TODO” markers for things like variables that it thinks arent used or for lines that might be missing a semi-colon (which often are not). All this clutter will hide your “TODO” markers. To turn off the yellow markers do the following:

Right click the Overview Ruler and choose “Preferences”:

Next click “Annotations”, then scroll down to the “Warnings” Annotation Type. Click “Warnings” and then deselect “Overview ruler”. Click Apply/Ok and your done.

Wildcard Searches with CTRL+F

Find/Replace is not so much of a tip as we’re all familiar with it. But, if you are like me and have a long history using Dreamweaver you may have learned how to take advantage of regular expressions in your search/replace activities. No worries, this little tip is simple – you can do wild card searches in your projects by using an asterisk (*) – as long as you check the “Regular Expressions” check box. This is especially useful if you employ naming conventions for variable and function names.

For example, if you know that you are looking for an ID but don’t recall the entire string, but know that due to your naming conventions that it starts with “txn” and its a “sheet” (a Sencha Touch-specific feature) you would search for all occurances of it by entering “txn*sheet” and then hit the Find button until you find what you’re looking for.

Jump to Last Edit with CTRL+Q

I use this more than anything else – simply jump back to your last edit point from anywhere in your code by pressing CTRL+Q.

Go to line using CTRL+L

Not much to say here – when I debug using Chrome with the developer tools turned on I can see where errors and my console.log statements appear within my code. Just look at Chrome’s console, note the line number, then zip straight to the line in Eclipse.

Filter LogCat

LogCat is where all your console.log statements appear within Eclipse – as well as a million other things happening on your phone or tablet. So much stuff shows up that the one thing that you’re interested in often just scrolls out of view. You can filter the LogCat window by typing in an expression where Eclipse indicates as much:

The easiest thing to do is to simply follow Eclipse’s direction and type the Prefix of what you are looking for and enough characters to get what you want. In our case, what we want is the Web Console. But thats two words with a space in between which won’t work (as you will discover). We can do something as simple as just “tag:web” which narrows down the list greatly:

Thats better – but not perfect. We see everything with the word “web” in its Tag, but all we want is the “Web Console”. To get there we need to write a Java regular expression – the entire string would be: “tag:^web\sconsole$”, as shown below:

And, if you are lazy, you can save your regular expression for later use by toggeling the Saved Filters View button illustrated to open the Saved Filters pane:

At this point, click the “Plus” icon and fill in the desired fields. Whenever you want to filter the log you can just click the Saved Filter View button to reveal your saved filters and select the filter that you want to apply.

Memory Allocation

Eclipse runs better with more memory, and what doesn’t? Thing is you might have 8 or 16GB or more in your dev machine but that doesn’t mean Eclipse is using it. The memory it uses is defined in the eclipse.ini file. If you get out-of-memory errors and the like you need to allocate more RAM to Eclipse.

On a standard Windows install, you will need to edit the ini file which is located in the root of your Eclipse install directory. This is a topic that others have expounded on better than I ever could so I’ll leave you with a link to a particularly good post on the topic:

Read more here: http://blog.xam.dk/?p=58.

Making a Phone Call from Within PhoneGap in Android and iOS

22 Feb 2012

Today I came across a feature request that I had not done before – dialing a number from within an app. Some quick research shows that its possible using a specific URI scheme.

What are URI schemes? Honestly Wikipedia does a better job than I ever could in describing them but I think of them as something that allows a specific piece of functionality to happen over the internet, and thus they are usually referred to as protocols. You probably have already seen them – the most common ones are http: and https: (for web browsing), and ftp:, among others. Some are unique to an application and really don’t qualify as schemes and are definitely not a “protocol”, such as mailto: (to open up the mail client on a person’s computer), javascript: or about: – in fact, try typing about: in the address bar of your browser and hit “enter” on your keyboard, notice what happens…

In our case where we want to dial a number from within our app we need a way of telling the mobile phone that we want to make a call. There is a scheme for this purpose called tel:. A sample number using this scheme would look like this: “tel:+1-800-555-1234”. If you wanted a number to work around the world you would use an international number which includes the country code.

Implementing this is simple, we could do this within our mobile html5 app like so:

...
call this number
...

Ideally though we would delegate the event and fire a function to call our mythical phone number. To send the url (the “tel” url) to the browser we would write the following:

...
document.location.href = 'tel:+1-800-555-1234';
...

As of PhoneGap 3.6 all schemes are subject to whitelists. This means you have to add the tel scheme to a second whitelist that will allow your app to launch external applications. To do this you need to edit your config.XML to include the following (a mailto example is included):



Go here for more information: Cordova 3.6.0 Whitelist Guide.

Of interest to this topic is getting Android to treat phone numbers (as well as URLs and mailto schemes) as clickable links in text fields. I’ve not tested it but try adding the following to your config.xml.


Additional information on this can be found here: http://developer.android.com/reference/android/widget/TextView.html#attr_android:autoLink.

[EDIT: Note that what follows no longer applies but remains here for historical purposes.]

When we run the above code in Android 2.3.6 the phone dialer appears and does so with our number pre-populated ready to be dialed. Unfortunately on iOS 5 this doesn’t happen. A quick review of iOS documentation implies that it should work – so I suppose its just broken.
No need to panic, there is a PhoneGap plugin available which will take care of things. The plugin can be downloaded from here:

Click here to download the iOS Phone Dialer PhoneGap plugin

Its simple to install – just drag and drop the “m” and “h” files on to the classes folder of your xcode project. When you do this a dialog will appear with some options – be sure to click the radio button for copying “…files if needed..”.

Next, update the PhoneGap.plist file to reflect that you are adding a new plugin. The link for downloading the plugin explains the plist values as being “phonedialer > PhoneDialer”… but I think its easier to explain with an image:

The final step is to place the “PhoneDialer.js” javascript file somewhere within the root of your project and then to add it to your index.html file via a script tag.

Now that the Phone Dialer plugin is installed you’ll naturally want to know how to use it:

...
window.plugins.phoneDialer.dial('1-800-555-1234');
...

All in all pretty easy and straight forward, however now you have two methods of dialing a number within a single project. What you want is to use the tel: url scheme in Android and the Phone Dialer plugin in iOS.

Within Sencha Touch we have something called the Ext.is object whose attributes reflect everything that you could possibly want to know about the environment that your mobile app is living within.

For our purposes all we want to know is if we are in iOS or if we are in Android. These two lines provide us the answer:

...
Ext.is.Android // boolean, "true" for android, false otherwise
Ext.is.iOS // boolean, "true" for iOS, false otherwise
...

Thats all we need to impliment phone dialing across the two platforms within our mobile app. Lets build a function that makes use of one of the above (we don’t need both) and we should also give the user a choice in the matter, so the code below includes a message to the user to see if they really do want to suspend the app in favor of the device’s phone dialer:

...
function callSomeone(){
    var msg = Ext.Msg.confirm('Please Confirm','Are you sure you want to make a phone call?',
        function(r){
            if (r == 'yes'){
                if (Ext.is.Android){
                    document.location.href = 'tel:+1-800-555-1234';
		} else { // we assume the device is running iOS
		    window.plugins.phoneDialer.dial('1-800-555-1234');
		}
	    }   
	});
    msg.doComponentLayout();
}
...

All done… I suppose the very last thing to do here is to provide a complete working Sencha Touch example, and some screen captures…

...
Ext.setup({
    onReady: function(){
	
        var rootPanel = new Ext.form.FormPanel({
	    fullscreen: true,
	        items: [
		    {
			xtype:'button',
			text:'Call 1-800-555-1234',
			scope:this,
			handler: callSomeone
		    }
		],
		dockedItems:[
		    {
			xtype:'toolbar',
			dock:'top',
			title:'Phone Dialer Example'
		    }          
		]
	    }
	);
	
	function callSomeone(){
	    var msg = Ext.Msg.confirm('Please Confirm','Are you sure you want to make a phone call?',
		function(r){
		    if (r == 'yes'){
		        if (Ext.is.Android){
		            document.location.href = 'tel:+1-800-555-1234';
			} else { // we assume the device is running iOS
			    window.plugins.phoneDialer.dial('1-800-555-1234');
			}
		    }   
		}
	    );
	    msg.doComponentLayout();
	}

    }
});
...

The final product on a Samsung Galaxy S2: