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

Maybe it would be appropriate to title this “how our government shows respect for workers rights”.  This of course in response to the Honourable Lisa Raitts’ continuous threats to legislate unionized workers back to work, this time being Air Canada flight attendants.

We are told this is because our economy is in a terribly fragile state and everyone needs to work, otherwise everything will crumble.  This is really a quite entertaining argument, especially since we have several other airlines that we can choose to go with instead if the flight attendants decide to go on strike.  So, as consumers there isn’t anything major to worry about if there is a strike.  We may be slightly inconvenienced because of this, but we do need to give the workers their right to fight for better terms in their collective agreement.

It’s extremely frustrating to see our members of parliament, let alone the Conservative party getting involved in private affairs like that of Air Canada or Canada Post.  In forcing these workers back to work we are taking away a strong part of their bargaining power.  The strikes are supposed to put pressure on an employer to make a better agreement since every day on strike is lost profit on their part.  Meanwhile, we have our government stepping into places they shouldn’t be involved with and passing laws that truly only benefit the employer.  Perhaps another benefit is it keeps canadians complacent despite the extremely damaging chilling effect this could have on other unions that will have lasting effects.

I’d like to thank Hon. Raitt for getting the union crushing snowball rolling.

I’ve realised that I haven’t posted about any of my homebrewing results in the last few months. To date I’ve made approximately 5 batches now, none of which are the same.

I’ve learned a fair amount and am far more prepared before I even begin boiling water. I’ve found the biggest part of making brewing an enjoyable experience is simply having a plan. What’s great about it, is that it doesn’t need to be anything complicated.  It just has to be enough to keep you from getting too stressed out.  For me, it typically consists of ensuring that I separate the tasks over several days so that I am able to focus on the task at hand.  Then brew day becomes a 2 hour event with little left to do after.

I’ve felt that each brew has gotten slightly better, with one exception…  It was a recipe for a wheat extract based beer.  We (my partner and I) figured it would be a good idea to give this a try since our thought process went something like this.

It’s going to have lemon in it, and honey, oh and it will be somewhere near 8%.  It’s going to rock!

It was a terrible idea.  From what I’ve discovered from other homebrewers; using honey has some pretty explosive results. In my case, because of all the sugar in the brew from  the malt extract and honey, the yeast went on a field day.  This resulted in the airlock getting gunked up, and the lid popping off leaving behind a wonderfully sticky mess to clean up.  If we look at it positively, at least we knew the yeast was working properly

The end result though, lead to a beer that had a high A.B.V. as we had expected but also still contained lots of sugars.  So it’s sweet, burns as it goes down, and has this really strange after taste.

Thankfully we have an ESB in the primary fermenter and I just bottled an IPA this morning so we’ll be back into familiar territory within a week or so.  Keep posted for the results!

Keeping up with my typical not at all on the subject mentality I did a presentation about Clojure at Septembers OGRE meeting.  There was some interest in getting the slides, as well as the resources I mentioned.  You can get the slides here (zipped up if you’d prefer that) and this is the list of resources I talked about.

 

  • Leiningen – https://github.com/technomancy/leiningen
  • Emacs Starter Kit – https://github.com/technomancy/emacs-starter-kit
  • 4Clojure – http://4clojure.com/
  • Intro Book: Programming Clojure – http://pragprog.com/book/shcloj/programming-clojure
  • Intermediate/Advanced: The Joy of Clojure – http://joyofclojure.com/
  • Lighter Approach: Land of Lisp – http://landoflisp.com/
  • “Clojure – Functional Programming for the JVM” – http://java.ociweb.com/mark/clojure/article.html

Last week at Shopify we had a this thing called FedEx Days (or something similar) where we were given 2 days to work on any project we wanted.  After having looked at the Jhopify library, and trying to patch it, I figured that API bindings for Shopify could be solved better.  I had worked with the Shopify API before when I first started working at Shopify while I was still doing Android dev there.  Since then though, nothing really came of it.

I had taken a few lessons from that experience and decided to use that knowledge to create a tool so that Android devs could spend less time writing boilerplate API code, and more time solving problems.  I also wanted to ensure that I could provide as much of a one-to-one mapping to the API as possible.  This meant one thing, Java Beans.  I looked at the API and looked at a blank Article.java file and cringed.  There has to be a better way to do this; and of course there is!  You see, I remembered reading something from the Pragmatic Programmer.  It’s something along the lines of “If you have to write repetitive garbage, why not have a computer do it instead? Voila! Code Generators!”.

Thankfully, the Shopify API provides some pretty good example output and I figured I would use this as a tool.  With the Shopify examples that I had so gracefully copy-pasta’d into some ‘fixtures’ that I was intending on using for tests I then proceeded to use them as training data.

So I fired up my default system text editor (TextMate, though emacs would’ve been preferable… no time!) and started hacking out some ruby.  First step was to get all the POJOs/beans written up, then I’d tackle actually getting the API to work.  This was pretty straightforward; read in the data, turn it into a hash, infer the data types and apply the various private members and their getters/setters, add annotations, etc.

But it dawned on me.  What if the Shopify API for say, Articles were to ever change? I could just manually add the new changes, but that sucks.  This reminded me of another problem I had when doing some iOS/core data work about a year ago which has much of the same problem, which was solved.  The tool that solved the iOS problem is known as MOGenerator.  The way the tool works is by inspecting your data model and creating intermediate classes with all the boilerplate, then adds a subclass where you can add custom code.  It makes the promise that if you ever put custom code in the _yourModel (or whatever syntax it uses), MOGenerator will gladly come in and overwrite all of it.  So I figured that taking a similar approach for the Shopify models would be fine, and would also save a bunch of time/worry.

With all that working and tests running green on some simple and more complex data types, I then proceeded to create the API bindings.  I decided to go with a tool called CRest which makes mapping API endpoints far simpler.  After writing the first endpoint I again realized that this could be generated as well, mind you not as elegantly.  Not all endpoints map out in a manner that is as simple as the beans, but I figured this is the best way to get at least some form of API wrapper working.  So making some really basic assumptions, I also generated all the endpoints.  These probably won’t work as elegantly as the beans did, but it should be a starting point for anyone wanting to work with the API.

So all in all, I was able to get hundreds of lines of code written up in about 200 lines of ruby.  Though we need to keep in mind that much of that ruby code consists of huge blocks of text and not actual logic.  If I were to remove all of that, I’d say this was accomplished in even fewer lines, perhaps 100?  I’m hoping to have the code publicly available on GitHub soon.  Just need to get a tutorial/demo app written up, unless you don’t care, then I may be able to convince some people to release it as is.

© 2011 Christopher Saunders Suffusion theme by Sayontan Sinha