So you’re interested in doing some Android development? Awesome, let’s get you set up and rolling out some apps. Everything is typically going well until you need to work with the SQLite database, then shit hits the fan. You’ve rolled out 2 or 3 versions of your app and because of the demos you’ve seen from places like the Android samples, changes are impossible to make without slightly breaking your brain.

Wouldn’t it be nice if we could represent our changes in a way that’s sane? We’ve seen this done in numerous frameworks such as Active Record or South.  Now, we don’t have to go this crazy with ORMs and having the code know how everything is related to each-other (though that is pretty awesome).  For now, let’s just focus on representing how our data model changes throughout various versions of our software.  So we could come up with some kind of Domain Specific Language for this problem, but this is still going overboard and may be a bit too complicated, let’s go simpler.  Instead, why don’t we simply use SQL and have a few rules (or conventions) that we need to follow to ensure that our databases migrations get applied properly?

Interestingly enough this is very easy to do and also results in database code that is easier to understand since well, it’s just SQL files!  Another advantage of this is you could simply have the SQLite binary installed on your system and load these files into a local database.  So you’ve also decoupled your database code from your Android application.  Sure, it’s still tied to the SQLite database, but at least you can play around with your database locally instead of in the emulator or on a device which can get a bit hairy if you don’t have the proper permissions (read: root access).

So, first let’s set up our migration files.  We’ll go with the convention of having them stored in assets/migrations. It will be our responsibility to ensure that our migrations are in that folder, and then our code will simply grab all migration files from that directory and load them. Now, we need to ensure some kind of ordering. We could go with the rails way of doing it, which is to add some kind of way to ensure all migrations are unique such as by using a very fine grained timestamp, but again, too complicated. Let’s simply go with a convention like NNNN_my_description_for_my_migration.sql where NNNN is a number between 0001-9999 (hopefully this will be enough for now!).

Awesome, so now we have a place to look and a way to order the migrations properly. Let’s actually figure out how to get these files loaded. I went with the simple approach of having the migrator do all of it’s work in the SQLiteOpenHelper.

First, let’s look at our DatabaseMigrator

public class DatabaseMigrator {
    private Context context;
    private SQLiteDatabase db;
    private AssetManager manager;
    private String[] migrations;

    public DatabaseMigrator(Context context, SQLiteDatabase db) {
        this.context = context;
        this.db = db;
        this.manager = context.getAssets();
        this.migrations = manager.list("migrations");
        Arrays.sort(this.migrations);
    }

    public void migrate(int from, int to) {
        for(String migration : migrations) {
            int version = DatabaseMigrator.version(migration);
            if(version > from && version <= to) {
                String migrationSQL = load(migration);
                apply(migrationSQL);
            }
        }
    }

    public static int currentVersion(Context ctx) {
        String[] migrations = ctx.getAssets().list("migrations");
        return version(migrations[migrations.length - 1]);
    }

    public static int version(String migration) {
        return Integer.parseInt( migration.substring(0, 4) );
    }

    public void apply(String sql) {
        db.execSQL(sql);
    }

    public String load(String migration) {
        ByteArrayOutputStream migrationBytes = new ByteArrayOutputStream();
        InputStream migrationStream = getMigrationStream(migrationStream);
        byte[] buffer = new byte[0x4000];
        int bytesRead = 0;
        while( (bytesRead = migrationStream.read(buffer)) > 0 ) {
            migrationBytes.write(buffer, 0, bytesRead);
        }
        return new String(migrationBytes.toByteArray());
    }

    public InputStream getMigrationStream(String migration) throws IOException {
       return manager.open("migrations/"+migration);
    }
}

Now for our actual database open helper.

public class MyApplicationsDatabaseOpenHelper extends SQLiteOpenHelper {
    private DatabaseMigrator migrator;
    private Context context;

    public MyApplicationsDatabaseOpenHelper(Context ctx) {
        super(ctx, "myAppsDatabase.sqlite3", null, DatabaseMigrator.currentVersion(ctx));
        this.context = ctx;
    }

    public void onCreate(SQLiteDatabase db) {
        DatabaseMigrator migrator = new DatabaseMigrator(context, db);
        migrator.migrate(0, DatabaseMigrator.currentVersion());
    }

    public void onUpdate(SQLiteDatabase db, int oldVersion, int newVersion) {
        DatabaseMigrator migrator = new DatabaseMigrator(context, db);
        migrator.migrate(oldVersion, newVersion);
    }
}

Now we do have a few caveats we should take note of first. The big one is that execSQL only runs the first SQL statement, which can cause some funky issues if we want to have a migration that creates several tables or makes many modifications. All we simply need to do is add something to ensure that our migrations can be cut up properly.

For example:

CREATE TABLE people(firstName, lastName);

/** Separator **/

CREATE TABLE animals(species, genus, class);

Turning this migration file into properly executable statements is left as an exercise for the reader.

 

I’ve recently been thinking of what differentiates a good from a bad programmer. Often people have used words like “elegant” and “simple” as ways of describing attributes of a good programmer. Though surely we can come up with a physical analog to draw a better comparison. Personally, I’ve found the analog to be cooking because it’s easy to tell a bad (or junior) cook from a good one.

Previously I was training in the military as a cook, so I’ve taken several courses that taught various skills such as organization, discipline and of course; how to work in a kitchen. Much of the kitchen work heavily revolves around how one treats their workspace. Of course this is important to ensure that the kitchen is safe and that there is no contamination, which can lead to extremely disgruntled clients. While my profession has drastically changed, I still take those lessons from my culinary experience and apply it to my own kitchen.

When it comes to my own kitchen I’ve noticed a pretty big disparity between how my partner and I prepare our meals, that being while she’s really good at creating the end product, the side-effects of her cooking are rather… messy. Anyone can be a good cook, it just takes a bit of discipline and the desire to keep your space as clean as possible. This of course includes things like having a sink full of hot, soapy water so that in between steps you can clean the tools you just used.

So you’re probably wondering what does any of this have to do with programming? Well if we compare how a good and bad programmer works, it’s quite similar to working in a kitchen. We all start with a clean slate and start combining the pieces to create the end product, though the good programmer will continue to return to their code and find ways to improve upon it. This can be anything from modularizing code, to simply taking a piece of code and making it simpler to follow.

A bad programmer on the other hand will leave their solutions because “it works” and they’ll get back to it eventually. The problem with this is your workspace gets more and more cluttered, increasing your chances of having your code contaminate other parts of the codebase and before you know it, your system is sick. Now you’re stuck with a semi-working system that they cannot understand because of all the short-cuts and bad decisions that were made but never taken care of.

Now, I do believe that like a bad cook, a bad programmer can be taught the proper way to build things. Just like trades people need to spend several thousand hours as an apprentice, developers also need to do this. Without the correct mentorship we are never given the guidance we need to grow into a good developer. Well, perhaps that isn’t entirely true, you’ll still have the chance to grow though it will take a bit longer and you may also build up some bad habits.

 

So it’s been about 3 years since I made the switch over to Macs, and I’ve been pretty happy with it. I have shell that doesn’t suck and all the goodness that comes with a UNIX-like operating system. The one thing that’s always bothered me a bit is the lack of good tiling window management. About 6 months ago I played with xmonad for a bit and really loved it, even to the point where I tried using it in XQuartz on Mac (which turned out to be a terrible experience).

I’ve somewhat managed to get away with it by using emacs for the most of my editing. While not of the same calibre as a TWM like xmonad, it gives me that frameless experience I like. The one disadvantage is the lack of a shell I could use (if there’s something better than eshell, OH PLEASE TELL ME!) so I’ve typically had emacs using 80% of my screen, and an iTerm window using the other 20%… or something. It’s been alright, though I hate having to switch out of one application into another run something then switch back, etc etc. This is where I decided to take the plunge and give tmux a shot.

For those who don’t know about it, tmux stands for “Terminal Multiplexer” and allows you to have multiple terminal sessions running, sort of like Spaces or Virtual Desktops except entirely text based. They also allow you to disconnect from a session while not actually killing the processes, which is useful for things like running something on a server (upgrading stuff, or running a really long query where timeouts may be an issue). The connecting/disconnecting part has been a pretty awesome life-saver for myself where I have a tendency to lose context and kill or close the wrong application which is most often my editor.

Along with the session management there’s the window or pane aspect as well, which I really just use as a tiling manager. It’s not as advanced as xmonad, but I’m spending more time in a single application (iTerm) where it’s drastically easier to switch between my applications.

Of course everything isn’t perfect! I still haven’t figured out how to get stuff from emacs into my clipboard, which kinda sucks though aside from some sort of minor issues like this, I’ve been pretty satisfied.

 

I’ve been using a certain Podcast application for a while, and I have it configured in such a way that it will only do updates on wifi and at 9:30 in the morning.  I have a tendency to only be connected to 3G so this leads to some pretty frustrating experiences.  Primarily, I’m getting notifications that updates couldn’t happen then I’m directed to a screen with no way of actioning on these problems.  Alright, so the software isn’t that great… but it’s sadly the best for what I need.

Though, I feel this software could be vastly improved if only the developer took a few steps to gracefully handle things such as connectivity (let’s admit it, lack of connectivity isn’t an exceptional case, it’s an expectation).  Add in configuration such as “Only download over WiFi” well now you’re going to need to elegantly handle how an update is performed.

In my app, STO on the Go I needed to perform daily updates though there’s a good chance that when the scheduled task hits the user may not have an internet connection (or only want to download updates over WiFi).  Awesomely, Android is a really loud system.  It’s yelling things **all** the time about various status changes, one of these being connectivity status changes.  I figured I would tie into this.

Tying into these services is extremely straightforward, first we need to tell our manifest that we want to listen in on some BroadcastIntents:

<receiver android:name=".receiver.ScheduleUpdateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

So now our <pre>ScheduleUpdateReceiver</pre> will get called each time the state of connectivity changes on the device. Keep in mind, you are going to need to keep the code as lean as possible until you are absolutely sure you need to do some heavy lifting! Nothing is more frustrating than an app that appears to be doing nothing but kills your battery.

Now it’s time for our service to actually do some stuff, this is where we will be asking a few questions.

 

public void onReceive(Context context, Intent intent) {
	ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	String doUpdateOnNextWifiConnection = context.getString(R.string.doUpdateOnNextWifiConnection);
	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

	if(!prefs.getBoolean(context.getString(R.string.performDownloadsInBackground), true)) {
		// User configuration -- No background Updating
		Log.d(DEBUG_TAG, "Updates are not permitted to run. Aborting");
		return;
	}

	boolean hasActiveWifiConnection = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();

	// Check to see if the intent that was fired was created by Android itself
	if(intent.getAction() != null && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
		// Did the last check fail due to lack of connectivity?
		boolean performUpdateOnNextWifiConnection = prefs.getBoolean(doUpdateOnNextWifiConnection, false);
		if(performUpdateOnNextWifiConnection && hasActiveWifiConnection) {
			runUpdate(context);
			// Alright, our update has run, time to reset our state so we don't attempt to download
			// another update next time the device gets an internet connection.
			prefs.edit().putBoolean(doUpdateOnNextWifiConnection, false).commit();
		} else {
			Log.d(DEBUG_TAG, "Update for connection to wireless access point will be ignored");
		}
	} else {
		// This is our scheduled update
		boolean canDownloadWithMobileData = prefs.getBoolean(context.getString(R.string.usenetworktype), true);
		boolean hasMobileDataConnection = (telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED);
		if((canDownloadWithMobileData && hasMobileDataConnection) || hasActiveWifiConnection) {
			runUpdate(context);
		} else {
			// So, we either don't have an internet connection or the user wasn't connected to WiFi when the scheduled
			// update was supposed to happen.
			// I chose to store this information in the shared preferences because it's pretty easy to do.  This could get
			// a little bit out of hand if you have more complex rules than what I have here.
			Log.d(DEBUG_TAG, "Cannot do a download over data and we don't have a wifi connection. On the next wifi connection, we'll do the download then");
			prefs.edit().putBoolean(doUpdateOnNextWifiConnection, true).commit();
		}
	}
}

So now we are able to handle the sort of special cases and deal with them almost immediately after a user has acquired a usable connection to the internet.

 
I’m working on a background service that is going to be triggered by the alarm manager.  I’ve set everything up for my broadcast receiver, though I’d like to test it without having to write a bunch of Java code.  After looking around a bit I’ve come across this am tool that appears to do what I need, though I don’t know how to create a specific broadcast intent.
Let’s say my BroadcastReceiver is com.foo.receiver.NiftyReceiver and I have it in my manifest file as <receiver android:name=”.receiver.NiftyReceiver” />
The documentation is a bit lacking on how to use the tool, but after a bit of confusion I’ve finally figured out how to get it working.
am broadcast -n com.foo/com.foo.receiver.NiftyReceiver
Note, you need to add the android:exported=”true” to your <receiver> otherwise android will spew this nifty little error message on you:
W/ActivityManager(16908): Permission denied: checkComponentPermission() reqUid=10066
W/ActivityManager(16908): Permission Denial: broadcasting Intent { cmp=com.foo/.receiver.NiftyReceiver } from null (pid=1411, uid=2000) requires null due to receiver com.foo/com.foo.receiver.NiftyReceiver
I’m pretty sure this isn’t anything new, but I personally found tools like am aren’t really documented that well.  Hopefully this will save someone else a bit of time in the future!
 

I’m visiting family over the holidays and am a big fan of Castle Crashers.  Unfortunately, V’s brother didn’t have it installed (nor any Microsoft Points).  I figured this would be a pretty simple affair: Add my card, buy the points, remove the card and call it a day. I am pleasantly surprised to see that I now cannot remove the card from his account.  From what I’ve researched, as long as auto-renewal is off there shouldn’t be any problems.  Though, still I get some kind of 80xxxxxx error.

Alternatively there’s a web portal you can access to remove payment methods as well.  Unfortunately, this also doesn’t allow me to remove the card.  Instead we need to log into the ‘parental account’ which is essentially a dead account.  What I find curious is how easily I could add a card to this account (without ‘parental’ permission or whatever), yet to remove the card is a whole different story.  I would love to know how many 12 year olds have added their mom’s credit card to their Live account for those sweet, sweet MS points.

So, here I am with my Credit Card tied to a Live account with no ability to remove the card whatsoever.  I can say that I’ve learned a few things from this; one of those being that I won’t be giving Microsoft (at least the Xbox division) any of my business until they clean up their half-working practices.

 

Earlier this week I finished reading my copy of The Net Delusion by Evgeny Morozov. I’ve always been rather skeptical of the claims about how Twitter and Facebook are being used as tools for revolutions. The Net Delusion is extremely critical of this very western assumption and uses several examples from the cold war (Samizdat, Radio Free Europe, etc.) as how these technologies really aren’t that effective.

Morozov also talks about the hypocrisy of the west (primarily America) in regards to censorship and monitoring of ones people. America has been very critical of authoritarian states in regards to freedom, but then allows various industries to censor its citizens when someone’s bottom line is at risk. These acts essentially put cards in the authoritarian states hands; “If you (America) can sensor its citizens when it’s convenient why can’t we?”

When I was nearing the end of the book it felt like it had run out of a bit of steam. Although it made going through the last few chapters a bit tough it is still an excellent read.

If you are looking for an interesting read over the holidays, or simply want to learn about the other side of “Internet freedom” then you probably won’t be disappointed.

 

I gave myself a personal goal around mid to late November; to finish an STO Android app with the dataset that Phil Casgrain had given me access to.  The app is now available on the Android market as STO on the Go though it’s almost impossible to find using the search.

I’m selling the app for $1.00 though there is a good chance it will be getting an increase in the next version, which will have at least maps and favourites features.

 

I’ve been working on a side project at Shopify recently and one of the things I had to take a converted JSON object and store it on disk as a cache. I’m typically working with NSArrays and other fancy things so I figured this is where I’d look for serializing that data into a plist on disk.

-(BOOL) saveArray:(NSArray*)itemsArray toLocationOnDisk:(NSString*)location
{
    BOOL saved = [itemsArray writeToFile:location atomically:YES];
    return saved;
}

Because I’m targetting iOS 5 I have this nifty new tool available, it’s NSJSONSerialization though there’s a bit of a caveat. The data that you get back from it isn’t actually objects of NSArray, NSDictionary although for all intents and purposes they behave like they are in your code.

There is another way to get around this though, what you can do is convert the array into an archived object like so.

-(BOOL) saveArray:(NSArray*)itemsArray toLocationOnDisk:(NSString*)location
{
    NSData *archivedItemsArray = [NSKeyedArchiver archivedDataWithRootObject:itemsArray];
    BOOL saved = [archivedItemsArray writeToFile:location atomically:YES];
    return saved;
}

Now all we need to do is re-convert that data into an NSArray, which is relatively straightforward.

// Deserialize the object back to an NSArray
-(NSArray*) getArrayFromDisk:(NSString*)location
{
    NSData *rawData = [NSData dataWithContentsOfFile:location];
    if(rawData == nil)
        // Assuming iOS 5 using ARC
        return [[NSArray alloc] init];
    return (NSArray*) [NSKeyedUnarchiver unarchiveObjectWithData:rawData];
}

Once you know about this, it’s pretty straightforward but trying to find answers on sites like StackOverflow for this kind of problem is a bit tricky since people often assume you are working with plain old NSArrays and such.

 

I’m beginning to work on an STO application from an API that was created by Philippe Casgrain.  The data was stored in a pretty big JSON file, and I decided that instead of breaking it into smaller pieces I would simply insert everything into an SQLite database.  Previously the only time I had worked with Android databases had simply been via insertions with ContentValues, which is a lot slower than I had thought at first.

Previously this is what I was doing

void insertData(List objects, SQLiteDatabase db) {
    ContentValues cvs = new ContentValues();
    for(Foo obj : objects){
        cvs.put("FooStringColumn", obj.fooString());
        cvs.put("FooIntegerColumn", obj.fooInteger());
        long result = db.insertWithOnConflict("Foo", null, cvs, SQLiteDatabase.CONFLICT_REPLACE);
    }
}

This works alright, though when you are generating thousands of entries from your JSON data it results in something that’s so slow it’s painful. At first I thought my problems were stemming from using the org.json tools included in Android so I switched over to using Google GSON instead, which did help reduce a ton of unnecessary garbage collection. Though, everything was still slow.

My database knowledge isn’t extremely deep, and I recall being able to compile PreparedStatements to speed up interaction with the DB. After a bit of searching on the internet I came across an alternative way of doing database insertion using this thing known as an InsertHelper. Using an InsertHelper is pretty straightforward, though it requires writing a bit more code than ContentValues, but it’s way faster.

void insertData(List objects, SQLiteDatabase db){
    InsertHelper helper = new InsertHelper(db, "Foo");
    final int fooStrCol = helper.getColumnIndex("FooStringColumn");
    final int fooIntCol = helper.getColumnIndex("FooIntegerColumn");
    for(Foo obj : objects){
        helper.prepareForInsert();

        helper.bind(fooStrCol, obj.fooString());
        helper.bind(fooIntCol, obj.fooInteger());

        helper.execute();
    }
}

To also help speed things up, I extracted all of my data first then inserted everything in a transaction. This helped reduce overhead and I was able to get the database initialized in about 10 seconds. Surely I can speed it up further, but for now this seems to solve my problems.

References

© 2011 Christopher Saunders Suffusion theme by Sayontan Sinha