Backing up wordpress automatically

I’ve had some difficulties getting the BackWPup plugin to work, it seems that you can’t backup everything in one job as the script takes too long to run and the server will terminate it, causing a failed job.

The 2 errors I was seeing are

  1. WARNING: Job restart due to inactivity for more than 5 minutes.
  2. ERROR: Uploaded file size and local file size don’t match.

Which led me to this post, which recommends a better way to structure your backup jobs, basically just split them out into content, plugins, install etc so they finish within the timeout threshold.

Deploying a grails application to Cloudbees

I spent much of last weekend experimenting with the grails framework, so I wanted to deploy what I had in the cloud. Theres a big tutorial on the IntelliJ IDEA documentation (the screenshots don’t seem to match my installation of IDEA, even though its the same version number).

There is a much easier way, providing you have the Cloudbees SDK installed, you can just run this one-liner :

grails war; bees app:deploy target/MyWarFile.war -a mycloudbeesusername/applicationcontainernamehere

The above will package the application as a war file, and then deploy it to your Cloudbees instance.

Obviously the IDE will bring some additional features to the deployment, but if you don’t care about that and just want to upload, the one liner wins hands down.

Deploying the android libraries into your maven repository

Maven is a fantastic build tool, and a great addition to anyone developing on the android platform, however one of the first hurdles that people often stumble upon, is when their project involves one of the SDK libraries, such as Google Maps.

You’ll most likely see something like this when you attempt to first compile the project :

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.597s
[INFO] Finished at: Thu Jul 19 10:28:12 BST 2012
[INFO] Final Memory: 7M/81M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project WifiSpotter: Could not resolve dependencies for project com.jameselsey.android.apps.wifispotter:WifiSpotter:apk:0.1-SNAPSHOT: Failed to collect dependencies for [com.google.android:android:jar:2.1.2 (provided), com.google.android:android-test:jar:2.2.1 (provided), com.pivotallabs:robolectric:jar:1.0 (test), junit:junit:jar:4.8.2 (test), com.google.android.maps:maps:jar:8_r1 (provided)]: Failed to read artifact descriptor for com.google.android.maps:maps:jar:8_r1: Could not transfer artifact com.google.android.maps:maps:pom:8_r1 from/to cloudbees-private-release-repository (https://repository-
[ERROR] jameselsey
[ERROR] .forge.cloudbees.com/release): IllegalArgumentException: Illegal character in authority at index 8: https://repository-
[ERROR] jameselsey
[ERROR] .forge.cloudbees.com/release/com/google/android/maps/maps/8_r1/maps-8_r1.pom

As we can see, maven is unable to find the maps artefact, and rightly so. This is because the Google jars are not available (at least not at the time of writing this) on the maven central repositories. Fortunately for us, its relatively easy to resolve this, we just need to obtain the artefacts from our android home area, and then install them to our maven repositories so our projects have access to them.

You could manually install all of them, but this would be quite a lengthy task, and relatively unnecessary with the help of the maven-android-sdk-deployer, this nifty little tool will extract the libraries from your local android SDK installation, and install them as maven dependencies, to your local repository. From there, you can just depend on them as any other maven artefact, such as :

<dependency>
  <groupId>android</groupId>
  <artifactId>android</artifactId>
  <version>4.1_r2</version>
  <scope>provided</scope>
</dependency>

There is no need for me to cover how to use this tool, since it is pretty well documented, however I would like to refer you to a previous post of mine regarding deploying maven artefacts to a CloudBees repository, combined with this post, you can quite easily and reliably maven-ise the android dependencies, and deploy them into the cloud. Then you can build your android projects using maven from anywhere, and also take advantage of the free Jenkins service they provide.

Remember to drop in the repository into the pom.xml, and then you can simply run :

mvn clean install deploy:deploy

Hope this helps, if anything is unclear, please let me know!

Deploying artefacts into your CloudBees maven repositories.

If you’re like me, and have a fair few hobby projects on the go at any one time, you’re may want to take advantage of some of the free cloud services that are available out there. I’m particulary fond of the Maven repositories that CloudBees offer, as it gives you a safe and easy way to deploy your artefacts, whether they’re 3rd party libraries, snapshots, or even releases of your own software.

Head over to CloudBees.com and register an account, its free.

I’ve recently been doing a fair bit of work 3rd party libraries that are not available on the maven repositories, you have to download the source and compile it yourself (I have another post about an example of that). Since I often develop on different machines, and I’m not actually changing the library, I wanted a single place where I could upload a pre compiled copy of it and just depend on it as I would any other library, such as JUnit.

The first task, is to get your project compiling and working locally, once that is done you can then add the following into your pom.xml

Repository (that references a configured repository on ~/.m2/settings.xml)

<repository>
            <id>cloudbees-private-snapshot-repository</id>
            <name>cloudbees-private-snapshot-repository</name>
            <url>dav:https://repository-jameselsey.forge.cloudbees.com/snapshot/</url>
        </repository>

Also, since maven 3 requires the webdav extension, you’ll need to add this into the build/extensions section of your pom.xml:

<extensions>
            <!-- Extension required to deploy a snapshot or a release to the CloudBees remote maven repository using Webdav -->
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-webdav</artifactId>
                <version>1.0-beta-2</version>
            </extension>
        </extensions>

After that, make sure that your ~/.m2/settings.xml file contains details of your CloudBees repositories, here is my copy, make sure you put your password in, and replace occurences of “jameselsey” with your own user ID.

<?xml version="1.0"?>
<!--
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.
-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
    <server>
        <id>cloudbees-private-snapshot-repository</id>
        <username>jameselsey</username>
        <password>YOUR_PASSWORD_HERE</password>
        <filePermissions>664</filePermissions>
        <directoryPermissions>775</directoryPermissions>
    </server>
    <server>
        <id>cloudbees-private-release-repository</id>
        <username>jameselsey</username>
        <password>YOUR_PASSWORD_HERE</password>
        <filePermissions>664</filePermissions>
        <directoryPermissions>775</directoryPermissions>
    </server>
    <server>
        <id>cloudbees-private-snapshot-plugin-repository</id>
        <username>jameselsey</username>
        <password>YOUR_PASSWORD_HERE</password>
        <filePermissions>664</filePermissions>
        <directoryPermissions>775</directoryPermissions>
    </server>
    <server>
        <id>cloudbees-private-release-plugin-repository</id>
        <username>jameselsey</username>
        <password>YOUR_PASSWORD_HERE</password>
        <filePermissions>664</filePermissions>
        <directoryPermissions>775</directoryPermissions>
    </server>
</servers>
<profiles>
    <profile>
        <id>cloudbees.private.release.repository</id>
        <activation>
            <property>
                <name>!cloudbees.private.release.repository.off</name>
            </property>
        </activation>
        <repositories>
            <repository>
                <id>cloudbees-private-release-repository</id>
                <url>https://repository-jameselsey.forge.cloudbees.com/release</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
        </repositories>
    </profile>
    <profile>
        <id>cloudbees.private.snapshot.repository</id>
        <activation>
            <property>
                <name>!cloudbees.private.snapshot.repository.off</name>
            </property>
        </activation>
        <repositories>
            <repository>
                <id>cloudbees-private-snapshot-repository</id>
                <url>https://repository-jameselsey.forge.cloudbees.com/snapshot</url>
                <releases>
                    <enabled>false</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </repository>
        </repositories>
    </profile>
    <profile>
        <id>cloudbees.private.release.plugin.repository</id>
        <activation>
            <property>
                <name>!cloudbees.private.release.plugin.repository.off</name>
            </property>
        </activation>
        <pluginRepositories>
            <pluginRepository>
                <id>cloudbees-private-release-plugin-repository</id>
                <url>https://repository-jameselsey.forge.cloudbees.com/release</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </pluginRepository>
        </pluginRepositories>
    </profile>
    <profile>
        <id>cloudbees.private.snapshot.plugin.repository</id>
        <activation>
            <property>
                <name>!cloudbees.private.snapshot.plugin.repository.off</name>
            </property>
        </activation>
        <pluginRepositories>
            <pluginRepository>
                <id>cloudbees-private-snapshot-plugin-repository</id>
                <url>https://repository-jameselsey.forge.cloudbees.com/snapshot</url>
                <releases>
                    <enabled>false</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </pluginRepository>
        </pluginRepositories>
    </profile>
</profiles>
</settings>

Now, if you run mvn clean install deploy:deploy, maven will create a clean build of your application, install it to your local repository, and then deploy it to your CloudBees snapshot repo.

[INFO] --- maven-deploy-plugin:2.7:deploy (default-cli) @ tess-two ---
WAGON_VERSION: 1.0-beta-2
Downloading: dav:https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/0.0.1-SNAPSHOT/maven-metadata.xml
Downloaded: dav:https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/0.0.1-SNAPSHOT/maven-metadata.xml (769 B at 0.7 KB/sec)
Uploading: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/0.0.1-SNAPSHOT/tess-two-0.0.1-20120720.120205-2.apklib
Uploaded: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/0.0.1-SNAPSHOT/tess-two-0.0.1-20120720.120205-2.apklib (5865 KB at 449.0 KB/sec)
Uploading: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/0.0.1-SNAPSHOT/tess-two-0.0.1-20120720.120205-2.pom
Uploaded: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/0.0.1-SNAPSHOT/tess-two-0.0.1-20120720.120205-2.pom (3 KB at 1.2 KB/sec)
Downloading: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/maven-metadata.xml
Downloaded: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/maven-metadata.xml (276 B at 0.6 KB/sec)
Uploading: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/0.0.1-SNAPSHOT/maven-metadata.xml
Uploaded: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/0.0.1-SNAPSHOT/maven-metadata.xml (769 B at 0.4 KB/sec)
Uploading: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/maven-metadata.xml
Uploaded: https://repository-jameselsey.forge.cloudbees.com/snapshot/tess-two/tess-two/maven-metadata.xml (276 B at 0.2 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 49.874s
[INFO] Finished at: Fri Jul 20 13:02:24 BST 2012
[INFO] Final Memory: 16M/81M
[INFO] ------------------------------------------------------------------------

The same should work for releases, just alter the repository in the pom to point to the releases repo. This isn’t particularly CloudBees specific either, it should work on any remote maven repository, I just like CloudBees, and no, I don’t work for them :P

Any comments/suggestions, please shout!

Sending Tweets from your iOS5 app, easy!

Sending a tweet from your iOS application could not be any easier, Apple and Twitter really were looking out for their developers.

With iOS 5, the twitter account is authenticated under the settings menu of the device, which means that any application can request this account to use for tweet, and that is all you need to do; sign in, then request these details in your application.

Follow these easy steps

Sign into twitter on your phone

Go to Settings > Twitter > Sign in, as displayed below

Enabling tweets from your application

Then from your application, make sure that you add the twitter framework in as a linked framework. You can do this by clicking the application target, select summary page, scroll down to “Linked Frameworks and Libraries”, then add a new one, searching for “Twitter”, this all comes bundled with the Xcode development environment.

One the framework is linked, you can now import the following header into your application, such as in any one of your ViewControllers:

#import <Twitter/Twitter.h>

Now, we just have to display the view for allowing the user to create a tweet. I usually append this onto a button click, but you could invoke it from any other event, such as the view appearing, a slider being altered, or even after a segue. This is my example for creating a tweet on a button click :

- (IBAction)postToTwitterClicked:(id)sender 
{
    if ([TWTweetComposeViewController canSendTweet])
    {
        TWTweetComposeViewController *tweetSheet = [[TWTweetComposeViewController alloc]init];
        
        [tweetSheet setInitialText:@"This is a sample tweet!"];
        [tweetSheet addURL:[NSURL URLWithString:@"http://www.Twitter.com"]];
        
        [self presentModalViewController:tweetSheet animated:YES];
    }
    else 
    {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Unable to tweet"
                                                     message:@"Please ensure that you have at least one twitter account setup and have internet connectivity. You can setup a twitter account in the iOS Settings > Twitter > login."
                                                    delegate:self 
                                           cancelButtonTitle:@"OK" 
                                           otherButtonTitles:nil];
        [av show]; 
    }
}

A little explanation of the above. First, we want to check if we have the capability of sending a tweet, this just checks to see that you have at least one account signed in. If you can’t send a tweet, do something to notify the user what is wrong, such as displaying an alert prompting them to sign in, otherwise the user will wonder why they can’t make a tweet.

Next, alloc/init a TWTweetComposeViewController, this is the controller that handles composing a tweet. You can set the initial message (the tweet contents). You can also set URLs, locations, and images, refer to the documentation for info on those.

Finally, present the view controller modally (sits on top of anything else). It should look a little like this :

Once you’ve sent a tweet, it will sound a bird chirp to let the user know it is successful.

Easy, its a little shame that the same cannot be said for Facebook…hopefully iOS6 may ease integration.

Top 10 Techie things I want to achieve in 2012

I’m not the type of person that gets bored easily, I’ve always got many things to keep me amused, mostly side projects at home. I’m a firm believer, that if you don’t set yourself goals in the first place, then you won’t have anything to fail to achieve, so I’ve set myself a list of targets that I’d like to achieve in 2012 knowing full well I probably won’t get around to them all, but if I can do at least 3, it was worth it.

SCJP

I first picked up the SCJP study guide sometime around 2008, and I’ve had a love-hate relationship ever since. It’s by no means a trivial read, in fact, over 800 pages of solid technical details, a fair chunk of which I’ve never actually used, and probably never will once I’ve got through the exam. Reading the book is not enough to get through the exam, you also need to spend countless hours writing small code snippets to back up understanding, and spend plenty of time in mock exam simulators to prepare yourself. I have a terrible habit of getting obsessively involved in studying for a few weeks, before something pops up (working extra hours on a recent project at work is one good example) and I’ll not touch the book for weeks, only to have to re-cover the chapter where I last left off. This is definitely my goal for 2012, if I achieve nothing else but this, I’d be contempt.

Update AndroidSam

I put my first android app out on the market earlier this year, since its release I’ve had some fantastic feedback, amassing well over 15,000 downloads in the first 6 months alone. The app was very much an experimentation, and I certainly cut a few corners in the UI department prior to launch. I’ve been working on a few look and feel improvements, and a few other tweaks that I’d like to get out there soon.

Become more active on JR and SO, and java black belt

This is a must, theres no end goal and its more of an ongoing task that I must do. StackOverflow is a technical Q&A site, I’ve mostly become involved on the questions asking side, but the site has almost doubled in size in recent years so now there are plenty of unanswered questions that I can sneak in answers to, so I’ll have to start sweeping through my tags and get answering. JavaRanch is also a great site, I read this daily, however I rarely leave any posts. I’m planning to get more active and try to chip in with my comments more often. JavaBlackBelt is yet another great site, I was invited to be a beta question creator on the android exam but I just didn’t get round to providing any content, perhaps I can get more involved in 2012.

Complete SCJP study write ups

I found that a good way to help remember topics when studying, was to try and blog about them. I took the index of the SCJP study guide and outlined all the topics, and then gradually made my way through them all blogging about them in my own words. When trying to explain something, you often realise how you know (or sometimes how well you don’t know a particular subject). I’m about halfway through, and I’d really like to complete the blog posts, and get as much of my sample code up onto my Github account so it can help others.

Read, digest, and blog about technical books

Books, I’ve got a whole shelf of books that need some time. The main 3 that I’m interested in reading in 2012 are Effective Java, Clean Code, and Pragmatic Programmers Guide.

Effective Java is basically a compilation of tips and tricks that a Java developer should use if at all possible, Clean Code tells you how you should be writing your code and approaching problems, and the Pragmatic Programmers Guide is just more theory to lay on top. They’re not trivial reads, and some of it may possibly be too advanced for me, but if I can take anything away from it, it should help my progression.

Finish off my other android projects

I’ve been using Evernote to brain dump app ideas, its a handy little tool. Sometimes you get ideas spring into mind at the most awkward of moments, but most of the time I have my phone to hand, so I just tap them into evernote and let my ideas develop. Right now, in my cooking pot of ideas, I’ve got about 6 apps that I feel are worth putting to code, most are utlitlies but I have a few heavyweight ideas in there. Hopefully I can progress these throughout the year and get at least a few out to market.

Explore Spring Web MVC

The first company that I worked at solely produced Java web applications, that was where I got my first taste for the likes of Struts, Stripes, and a little bit of Spring MVC. I particularly liked working with the Stripes MVC framework, but it did lack a lot of community support, I’d like to explore a little with Spring MVC, since it’s always handy to know how to use the basics of Spring anyway. I started writing my own sales tracking system on Google App Engine, perhaps I’ll do something similar with Spring MVC and host it in the cloud somewhere.

Complete a cloud based CI environment

I’ve got various little side projects on the go, sometimes I use my windows PC at home to work on them, sometimes my works laptop, or my linux machine, so it can be a bit of a pain managing source code and builds. Fortunately I discovered something called Unfuddle, an online SVN repository where I could check my code into. I’ve also discovered something called CloudBees, which is a free on-line Jenkins installation, I’m planning to use that to build all my projects in the cloud, and dump artefacts onto DropBox. I may look at maven repositories too. Ultimately, I want to get my build processes in the cloud, so its purely coding that happens outside the cloud.

Ubuntu Certification

OK so one certification in the year is optomistic, but what about two? I’ve been an on-off linux user since I was in college, only really dipping back into Windows when I go through phases of gaming (WINE is just too much effort). Being competent with the shell terminal is going to help in the long run, so why not dedicate some time to skilling up in something useful. I’m not sure if I’d specifically go for the UCP, but it seemed an obvious choice since I have some familiarity with Ubuntu.

Explore Android ICS

With the latest Ice Cream Sandwich android released, theres plenty to be experimenting with, even if theres only a handful of devices that support it. I imagine that ICS will become more and more supported as the year goes on, so its probably time for me to devote some hours into picking up the new features of the SDK, and coming up with something nice. I’m also desperately in need of upgrading my 2.1 Orange San Francisco sub £100 handset, so possibly an excuse for a nice new shiny upgrade?

Revisit GAE Sales Tracker

About 2 years back I began working on an open source sales tracking system, to monitor progression of sales prospects. I started this in Stripes MVC framework and deployed to the Google App Engine. At the time GAE was still in its infinacy, but after a few years and several upgrades, I think developing on this platform may be slightly less painful now. I still have all the source code, and still have a running demo, maybe I can pick it up again and see what GAE improvements have come around.

Android; how to display a map the easy way..

I’m seeing countless questions, literally on a daily basis on StackOverflow regarding using maps on Android. To be honest I’ve never come across these problems but it seems many people have trouble using the maps in their application, so I’ll provide a clear and easy set of instructions on how to do this.

Common issues

  1. API key is incorrect
  2. You are using the standard Android emulator and not the Google APIs.
  3. You have extended Activity instead of MapActivity

The Tutorial…

The first thing you need, is an application to put your map in. For this tutorial I’m suggesting that you just create a blank android project, to get familiar with how maps work, then you can shift it into your existing application. Using IntelliJ (or Eclipse, if you must), create a new android project. I’ve called mine “MapMe”.

This will give you just one activity, such as the following :

package com.jameselsey.mapme;

import android.app.Activity;
import android.os.Bundle;

public class MapMe extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

I’d also suggest that you run this auto generated project to make sure your emulator starts up OK and you generally have a stable platform to build upon.

Next, we need to alter the emulator. The standard emulator that you get is the “android emulator”, which doesn’t allow you to use maps (at least not easily). This means that you need to create a slightly different emulator which does allow you to use maps, its quite easy.

Open up the android AVD manager (where you can create emulators / Android Virtual Devices). Click on the “available packages” option and download something called “Google APIs”, that should take a few minutes. When that is done, create a new AVD, be sure to check the “target” and make sure it is set to Google APIs. Once you’ve setup this emulator, make sure that your project is actually set to use it, by checking your run configurations and the target emulator.

Once thats done, I’d suggest you re-run the base application we’ve just created to make sure its all still OK.

OK so before we can finally jump into some code, you’ll need to go off and get an API key. This key allows you to use the Google maps API, I won’t explain how to do that here since theres already a rather good writeup from Google themselves, so go off and do that now.

Right lets hop into some code again, first thing you need to do is to add INTERNET permissions and uses-library into your AndroidManifest.xml file, mine looks as follows :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.jameselsey.mapme"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="MapMe" android:icon="@drawable/icon">
        <activity android:name="MapMe"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="com.google.android.maps" />
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest> 

Next, go into main.xml under res/layout and add the following :

<com.google.android.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="YOUR_API_KEY_HERE"
/>

Now we can start doctoring our activity.

Firstly, add the following import

import com.google.android.maps.MapActivity;

And make sure that you implement the method you inherit from MapActivity :

@Override
    protected boolean isRouteDisplayed()
    {
        return false;
    }

That is pretty much it, all you need to do now is to run the application, you should have the following end result :

Complete Source

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.jameselsey.mapme"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="MapMe" android:icon="@drawable/icon">
        <activity android:name="MapMe"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="com.google.android.maps" />
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest> 

res/layout/main.xml

<com.google.android.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="YOUR_API_KEY_HERE"
/>

MapMe Activity

package com.jameselsey.mapme;

import android.os.Bundle;
import com.google.android.maps.MapActivity;

public class MapMe extends MapActivity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected boolean isRouteDisplayed()
    {
        return false;
    }
}

Common Issues

Problems with RuntimeException : stub

java.lang.RuntimeException: stub
   at com.google.android.maps.MapView.<init> (Unknown Source)

You need to make sure that

<uses-library android:name="com.google.android.maps" />

is a child of the application tag.

Problems with importing of the com.google.* package

You may come across the following error :

java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation

If there are problems with that import (com.google.*), chances are you don’t have the maps.jar on your class path. Go back into your AVD manager, check available packages, under 3rd party libraries you should find some libraries from Google Inc., download those. If that still doesn’t solve your issue, then double check that your android “facet” is correctly using the Google APIs target.

Also, make sure that you don’t have 2 copies of the maps.jar on your class path, if you already have the target specified to Google APIs, then you don’t need to implicitly specify maps.jar on the classpath.

Maps are displaying, but all I see is grey squares…

This is most likely because you have the wrong API key, please go and re-generate that again to make sure its OK.

Further Reading

  1. Official Google Documentation
  2. MobiForge Tutorial

Integrating your wordpress into twitter and facebook, the easy way

I’ve been searching for a viable and easy solution for integrating my wordpress posts into facebook and twitter for some time now, and have finally found an easy solution, it takes about all of 10 minutes to setup. Twitter is essentially the “integration hub” in this process

What I’m trying to achieve : When I post a new blog post onto my wordpress site, I want it to appear in a tweet on my twitter account (with a link), and then to also appear on my status/wall on my facebook account.


What you need to do :

Connect facebook to twitter

  1. Login to your facebook account on facebook.com
  2. Search for the twitter app, install it and grant it access
  3. Make sure you select the option to post tweets to status/wall
  4. To prove this step worked, login to your twitter account and tweet something, then check facebook, it should appear on your wall / status page.

Connect wordpress to twitter

  1. Firstly download the twitter tools plugin for wordpress, I had a difficult time finding it via the wordpress plugin control panel, so it may be easier to just download the zip
  2. Login to your wordpress blog, navigate to the plugins control panel and upload the twitter-tools.zip
  3. Follow the configuration instructions that the plugin provides (its really simple, just obtain some keys from the links it provides)
  4. Once the plugin is connected using the API keys, go to the Settings control panel in your wordpress, and configure how you want the tweets to display. I chose to only allow one way integration, meaning wordpress to twitter, and not the other way around ie twitter tweets becoming wordpress posts.
  5. Finally, if you go back into your Plugins contorl panel, you will notice other twitter tools plugins that came bundled, you can activate these for additional functionality. I would recommend setting up the bit.ly integration for shorter URL links, as tweets are restricted to a short length this will allow you to have URLs for larger blog titles
  6. Finally, give it a spin! Create a new wordpress post, publish it, and check it first appears on twitter, and then facebook pulls it through

Good luck!

Tutorial; How to call Yahoo! REST web services the easy way!

I’ve got some requirements where I need to call a REST web service from an Android device, so I figured I’d get back to basics, and try to call a REST service through a simple Java application, just to see if I can get it working.

After trawling the web for what seemed like hours, I was finally able to come up with a simple yet effective solution. Consider the following

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * This simple class demonstrates how to call a 
 * REST web service provided by Yahoo! Developer Network APIs
 * @author james.elsey
 * @date 05/October/2010
 */
public class RestTest {

	public static void main(String[] args) 
	{
		
		String yahooAppId = "sam.A2DV34EOgopFWeVeqLVnaoTVmEIVZnVtd58o5IRCsZ4kcwBTSp4gVl9E7hnnbRxDgRo-";
		String URL = "http://where.yahooapis.com/geocode?location=701+First+Ave,+Sunnyvale,+CA&appid=";

		String URLtoCall = URL + yahooAppId;
		
		try 
		{
			String responseString = httpGet(URLtoCall);
			
			// Do something with the returned response, currently just printing to console
			System.out.println(responseString);
		} 
		catch (IOException e) 
		{
			// Handle exception here, currently just printing stack trace
			e.printStackTrace();
		}

	}
	
	/**
	 * Call URL and buffer response into a String
	 * @param urlString URL to be called
	 * @return String The response XML String
	 * @throws IOException
	 */
	public static String httpGet(String urlString) throws IOException 
	{
		  URL url = new URL(urlString);
		  HttpURLConnection conn =
		      (HttpURLConnection) url.openConnection();

		  // Check for successful response code or throw error
		  if (conn.getResponseCode() != 200) 
		  {
		    throw new IOException(conn.getResponseMessage());
		  }

		  // Buffer the result into a string
		  BufferedReader buffrd = new BufferedReader(
		      new InputStreamReader(conn.getInputStream()));
		  StringBuilder sb = new StringBuilder();
		  String line;
		  while ((line = buffrd.readLine()) != null) 
		  {
		    sb.append(line);
		  }

		  buffrd.close();
		  conn.disconnect();
		  return sb.toString();
	}
	
}

This simple piece of code will create a URL to be called, call it, and print out the result which in this case is an XML String. This is a particualry basic way of consuming a REST service, and using 3rd party libraries such as Apache HTTP Commons may provide a cleaner and more effective solution

This will give you a XML String response, its up to you how you deal with the response, you can parse it using SAX for example. In my next tutorial I’ll look at parsing, and how we can intergrate this all with an Android application

I was quite impressed with the documentation and support provided by the Yahoo! Developer Network, I will certainly be using this more frequently as their web services are easier to use than Googles, which is an odd occasion

JSTL Expressions ignored by Google App Engine, how to fix that..

So, you’ve written a nice J2EE application and have uploaded it onto the GAE only to be upset that your nice variables are displaying as ${contact.firstName} for example? No worries, its a simple issue, GAE seems to ignore expression language by default and all you need to do is to add the following line into your JSPs.

&lt;%@ page contentType=&quot;text/html;charset=UTF-8&quot; language=&quot;java&quot; isELIgnored=&quot;false&quot; %&gt;

Commit that and you’re good to go ;)