Including ActionBarSherlock as a Git submodule

If you’re using the ActionBarSherlock library in your Android project you can easily stay up to date by including it as git submodule.

$ cd /path/to/project
 
# Initialize the submodule 
$ git submodule add https://github.com/JakeWharton/ActionBarSherlock
 
# Commit your changes
$ git commit -am "Added ActionBarSherlock submodule."
 
# Ignore local changes in the submodule directory
$ git status --ignore-submodules=dirty

To ignore changes to the submodule directory (in case permission or other changes are required) you can add the following to your .gitmodules file:

[submodule "ActionBarSherlock"]
	path = ActionBarSherlock
	url = https://github.com/JakeWharton/ActionBarSherlock
        ignore = dirty

Installing Jenkins on an Ubuntu Amazon EC2 instance

Note: This post was written over four years ago and may no longer work correctly. This post will remain published for posterity.

This tutorial assumes you have already created an Amazon EC2 instance and are able to ssh to it. In our case, we used the Quick Launch Wizard to spin up a 32-bit instance of Ubuntu Server Cloud Guest 11.10 (Oneiric Ocelot).

Once you have a running EC2 instance you’ll need to modify the instance’s security group to open up ports 22, 80 and 443.

The first thing I did was update the EC2 timezone to our local timezone:

$ sudo ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime

Install any version control systems you might like to use:

$ sudo apt-get install git

Then pretty much just follow the installation instructions from the Jenkins Wiki. I’ve copied the actual steps here for posterity.

Installing Jenkins:

$ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -
$ sudo sh -c 'echo deb http://pkg.jenkins-ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list'
$ sudo aptitude update
 
# Note this will install the openjdk dependencies automatically!
$ sudo aptitude install jenkins

Setting up an Apache Proxy for port 80 -> 8080:

$ sudo aptitude install apache2
$ sudo a2enmod proxy
$ sudo a2enmod proxy_http
$ sudo a2enmod vhost_alias
$ sudo a2dissite default
$ touch /etc/apache2/sites-available/jenkins

Use your favorite editor to update /etc/apache2/sites-available/jenkins with the following virtual host configuration:

<VirtualHost *:80>
	ServerAdmin webmaster@localhost
	ServerName ci.company.com
	ServerAlias ci
	ProxyRequests Off
	<Proxy *>
		Order deny,allow
		Allow from all
	</Proxy>
	ProxyPreserveHost on
	ProxyPass / http://localhost:8080/
</VirtualHost>

Enable the new jenkins virtual host and restart apache:

$ sudo a2ensite jenkins
$ sudo apache2ctl restart

Jenkins should now be live and accessible from port 80! Now you can begin configuring Jenkins to your liking. I’ll follow-up with a post highlighting our Jenkins configuration. For now, here are the plugins we’ve chosen to install:

  • Green Balls
  • Post build task
  • Instant Messaging Plugin
  • IRC Plugin
  • Rake plugin
  • Git Plugin
  • Github Plugin
  • GitHub API Plugin
  • Github OAuth Plugin

The iPad bias and the Samsung Galaxy Tab

Samsung recently announced the release of their new mid-sized 8.9-inch Samsung Galaxy Tab (starting at $469 for the 16GB model). Personally, this is a device I’m very excited about. As an Android developer I’ve been dismayed by the lack of a good Android tablet, one that I actually want to own myself. The Motorola Xoom is powerful, but it’s ugly and unwieldy. The 10.1-inch Galaxy Tab looks promising, but like the Xoom, it’s just a bit too big for my liking.

Enter, the 8.9-inch tablet. Just a bit smaller than the Galaxy Tab, but packing the same hardware, it’s amazing they could fit all that into such a small package. Sounds like just the right size for me.

Now, here’s the disgusting part, the media coverage. The Galaxy Tab has been lambasted by bloggers for being too expensive. Ricardo Bilton over at ZDNet says this about the new 8.9-inch tab:

Interested in picking one up? We didn’t think so. With a screen size smaller than that of the iPad, Samsung’s asking price for its 8.9-inch tablet is a hair short of absurd.

Absurd, really? Since when does bigger equal better in the tech world. Has miniaturization not always been the goal of hardware engineers? Let’s look at the specs.

Surprisingly (or maybe not) the two devices have very similar hardware. Both tablets are available in a 16GB and a 32GB model; both run a 1GHz dual-core processor; both have equivalent WiFi support; both have a front and rear facing camera; both have bluetooth support and both can play full 1080p video and most of your favorite audio and video formats. Seeing a trend here?

Now, some of the major differences. The iPad 2 has a 9.7-inch (diagonal) screen with a 1024 by 768-pixel resolution, while the Galaxy Tab 8.9 has an 8.9-inch (diagonal) screen with a 1280 by 800-pixel resolution. The devices are both about the same thickness 8.8mm for the iPad 2 and 8.6mm for the 8.9-inch tab, but the tab is much lighter at 447 grams versus 601 grams for the iPad 2. The iPad 2 of course runs Apple’s iOS operating system while the 8.9-inch tab runs a skinned version of Google’s Android 3.1 (Honeycomb) tablet OS.

So here’s my question. Why on earth would anyone expect an .8-inch difference in screen size to equal a discount of several hundred dollars? This is not a discount tablet and in this case the size is more of a feature than anything. The 8.9-inch galaxy tab is absolutely as high-end a tablet as the iPad 2. It packs almost exactly the same hardware into a slightly smaller, slightly different form-factor. It runs a different, though equally capable and complex Operating System (Android) and offers an alternative to Apple’s walled garden app-store.

Seriously people, can’t we all just be civilized and have an adult conversation about our toys? Both devices obviously appeal to different sets of consumers. It’s about damn time we had a high-end piece of hardware in a svelte package running Google’s latest and greatest. Now if only we could get Samsung to offer a TouchWiz free model.

Sources

Add mercurial or git changeset id to your Android app

We recently automated the debug builds of our Android app. As a result, we wanted to include the Mercurial changeset id in our app settings, so we could quickly tell what version of the app someone was running.

What we ended up doing was writing the changset id to a custom properties file that was then copied into the raw directory during a build. That properties file could then be read by our PreferencesActivity on runtime.

In order to do this we wrote a custom build.xml file for ant. Simply copy and paste the following into your build.xml file:

    <!-- Require the hg.revision task during pre-build -->
    <target name="-pre-build" depends="hg.revision" />
 
    <!-- Check to see if a mercurial repository exists in the source dir -->
    <available file=".hg" type="dir" property="hg.present" />
 
    <!-- Get the mercurial changeset id for tip -->
    <target name="hg.revision" description="Store mercurial revision in ${repository.version}" if="hg.present">
        <exec executable="hg" outputproperty="hg.revision" failifexecutionfails="false" errorproperty="">
            <arg value="id" />
            <arg value="-i" />
            <arg value="-n" />
            <arg value="-r" />
            <arg value="tip" />
        </exec>
        <echo message="Repository version is ${hg.revision}" />
 
        <!-- Create property file containing mercurial changeset id -->
        <propertyfile file="version.properties" comment="The changset id that this app was built from.">
            <entry key="changeset" value="${hg.revision}" />
        </propertyfile>
 
        <!-- Move property file to app accessible res/raw/ directory -->
        <move file="version.properties" todir="res/raw/" />
    </target>

Essentially this creates an executable task that calls hg id -i -n -r tip in the build workspace. It then adds the result of that command to a propertyfile called version.properties. That file is then copied to the res/raw/ directory.

Our app code is even more straightforward. We simply wrote a function to retrieve the changeset id from the properties file in the raw resources directory. We then take the output of this function and update the preference item.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
 
        // Display app_build in settings as set in the app.version properties file at build time
        Preference build = findPreference("app_build");
        build.setSummary(this.getAppChangsetFromPropertiesFile());
    }
 
    public String getAppChangsetFromPropertiesFile() {
        Resources resources = getResources();
 
        try {
            InputStream rawResource = resources.openRawResource(R.raw.version);
            Properties properties = new Properties();
            properties.load(rawResource);
            return properties.getProperty("changeset");
        } catch (IOException e) {
            Log.e(TAG, "Cannot load app version properties file", e);
        }
 
        return null;
    }

OS X Lion Time Machine backup to Debian

When OS X Lion was released I was eager to try out the updated FileVault and Time Machine features. Moving from an encrypted home directory to true full-disk encryption was a dream. I was also quite excited to find out if the new implementation of FileVault would work well with Time Machine.

I’d previously set up a Time Machine volume on my Debian file-server by installing netatalk and avahi.

Unfortunately, it seems OS 10.7 (Lion) requires netatalk 2.2, which is currently in beta. However, it’s quite simple to install the beta version of the package and it seems to run just fine.

To install netatalk 2.2~beta4-1 you’ll need to add the following line to your /etc/apt/sources.list file:

deb http://debian.oregonstate.edu/debian sid main

You can also use any of the mirrors listed here if they’re closer.

Then run the following commands to install or upgrade netatalk:

$ sudo apt-get update
$ sudo apt-get install netatalk

If you had a previous install of netatalk it may detect changes to your local configuration files. By default the installer will keep the local copies of your files. This behavior is fine in this case.

After the install has finished run $ dpkg -s netatalk | grep -i version to ensure it was successful.

The netatalk service will be restarted by the installer after it completes. You may need to give it a few seconds to spin back up before trying to connect to it.

Your Time Machine backups in OS X Lion should now work correctly!

At this point you may want to comment out or remove the line you added to /etc/apt/sources.list so that you don’t inadvertently upgrade other packages to an unstable branch. After removing the line simply run $ sudo apt-get update one more time.

Update: Found the official Netatalk documentation.

Update 2: Here is the contents of both my afpd.conf and AppleVolumes.default files.

Update 3: Unfortunately, I can’t really provide support for any issues you might have with this. However, please keep your comments coming if you think they’ll be useful for other users attempting to get this working for themselves.

Android app build automation with Jenkins

In a nutshell, Jenkins provides an easy-to-use so-called continuous integration system, making it easier for developers to integrate changes to the project, and making it easier for users to obtain a fresh build.

This post assumes you have a working ci server running Jenkins (or Hudson).

First download and install the Android SDK to your Hudson server. Make sure it’s in a directory that’s accessible by your Hudson user.

$ sudo su hudson
$ cd ~/
$ curl -lO http://dl.google.com/android/android-sdk_r11-mac_x86.zip
$ unzip android-sdk_r11-mac_x86.zip

After unpacking the SDK you’ll need to install the individual Android platforms.

$ cd android-sdk-mac_x86/
$ android update sdk --no-ui

Now go get some coffee or take a smoke break, this is going to take a while.

Phew. Okay, now that’s done we can configure our new Hudson task. I’m going to assume you’re somewhat familiar with boot strapping a new project in Hudson, so I’m going to gloss over some of the details. Just make sure it’s pointed at your Android app’s source code repository.

In the build section of the project config you’ll want to specify a new “Execute Shell” build step with the following script.

# Ensure the SDK is in the Hudson user's system path
PATH=/Users/hudson/android-sdk-mac_x86/tools/:$PATH
 
# Change to the Hudson workspace directory
cd $WORKSPACE
 
# Create the required build files in the workspace
android --verbose update project --path .
 
# Execute the build
ant clean debug
 
# Copy the apk out of the workspace so your testers can get at your fresh build
scp bin/YourAppName-debug.apk foo:bar/

Pro Tip: Add this build script to your code repository and simply execute that script from Hudson. That way you can track your changes.

Note that if you’ve bundled extra libraries into your app you may see a build error when running this code. If so, try executing the ant build with the -lib option like so.

$ ant clean debug -lib foo/bar/libdir/

If you get into trouble, know that you can execute this build from the console as the Hudson user. Try running through the script manually first so you can identify any errors.

Update (2012-02-01): After living with this set up for a few months we started to run into some issues. It turns out, running your Ant builds from a shell script means Jenkins won’t always notice that your builds are failing. We also started running JUnit tests that, when a test failed, did not also trigger a build failure.

As a result we discovered that it was far better to run your Android builds using the Jenkin’s Ant Plugin. This allows you to invoke a series of Ant commands like clean debug or clean release. Jenkins will also format the Ant output and properly mark your build as failed or successful.

You can also take advantage of the Post Build Task plugin to run a script after your build is successful. This is useful for copying your .apk files elsewhere.

Don’t forget to run $ android update project --path . before your Ant commands are invoked, or your Android SDK folder may not be properly linked to your project.

Update (2012-09-06): The Android Emulator Plugin for Jenkins is a great tool that will help you manage the Android SDK on your CI server. It’s a far better option than installing the tools yourself. While you’re at it, you should check out the Android Lint Plugin to make sure your project is in tip-top shape.

Update (2012-03-02): I recently did a talk on Android build automation with Ant and Jenkins at the 2013 Snow-Mobile conference in Madison, Wisconsin. You can view the slides from the talk online at docs.google.com/presentation/d/19ddXSEVfd6-bGItNfROJMlL6O2rA1XOcRiBdE3NpgV4/edit?usp=sharing.

Localized Javascript countdown

These days many websites use a simple Javascript countdown clock to help promote the launch of a new service. Because many web applications are international, it’s important to ensure that your countdown is localized for all visitors.

Let me give you an example. Say you’re in Portland, OR and you’re launching a new web app on April 27, 2011 at 5:00 p.m. PST. Not only are you launching a new web service, but you’re also coordinating an iOS and an Android app launch. So it’s important to be precise. You want to ensure your Hong Kong visitors don’t expect your product to be launching at 5:00 p.m. HKT. Instead, you want them to know that your product is actually launching at April 28, 2011 at 8 a.m. local time.

One good way to do this is using the Date.UTC Javascript method.

// Get the current local time
var now = new Date();
 
// Get the localized end date for your countdown
var end = new Date(Date.UTC(
    2037, // Year
    3-1,  // Month (0 is January, so 3 minus 1 is 2, which is March)
    31,   // Day
    19,   // Hour
    0,    // Minutes
    0,    // Seconds
    0     // Milliseconds
));
 
// Toggle countdown
if (now < end) {
    // Show countdown
    alert(now + " < " + end);
} else {
    // Yay! We launched!
    alert('Launch day!');
}

If you run the script above, you’ll notice that while now is always increasing, end should stay constant. The only reason the value of end should change is if you change your computer’s local timezone.

You can now take these variables and pass them into a nice Javascript countdown script. I’ve used Keith Wood’s jquery.countdown.js jQuery plugin in the past, but I leave that decision up to you.

Multiple Base Templates in Django

I’ve been working on a pretty big project at work that’s heavily oriented towards mobile devices. We have a Django site running with a lot of custom ecommerce code, but wanted to serve up an optimized experience for mobile devices.

There are a lot of ways to do this, but ultimately we wanted to serve up a different base template for visitors on small-screen mobile devices. We wrote a piece custom view middleware that sets request['is_mobile'] = True. Unfortunately, Django currently requires any {% extends %} template tag to be the first tag in your template. This means you can’t do something like this:

{% if request.is_mobile %}
    {% extends 'mobile_base.html' %}
{% else %}
    {% extends 'default_base.html' %}
{% endif %}

After racking my brain all day my coworker suggested trying the yesno template filter. It worked like a charm!

{% extends request.is_mobile|yesno:"mobile_base.html,default_base.html" %}

So in our view templates we now do {% extends 'base.html' %} which then loads the proper base template depending on the status of is_mobile.