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 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’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

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.

I recently discovered that although PhoneGap is pretty awesome, there are some things you should know before you go out and try to get it working on your melange of devices.

phonegap.js isn’t all that you expect it to be. That is to say, phonegap.js for an iPhone isn’t the same phonegap.js that is used on Android. So, if you are going to be dropping phonegap onto a bunch of different devices while testing, be sure that you are using the proper javascript file. Otherwise you will be stuck scratching your head wondering why the camera works on platform X but not platform Y.

They are hoping to get that taken care of in the future, but for the time being you’ll have to be sure that you are using the proper file.

So DROIDHACK was this weekend, and I wasn’t exactly too sure what I wasn’t too sure what I was going to work on. I really wanted to get into the data layer of Mercury, but was really really dreading having to write all the data layer junk that comes with working with SQLite on Android.

Back when I first started working at Shopify I was initially going to be making an Android application. The first thing I knew I needed to do was find some kind of ORM that would make working with the database less painful. I had come across a few options, where the best was a proprietary one which I didn’t think was the best choice. Alternatively, there were a few open source projects that at first glance seemed like a good choice but were using way too much reflection and was kinda difficult to add features to. I really wanted a tool that would make it easy to create a database, but wouldn’t rely on reflection too much.

Another attendee, Don Kelly wasn’t too sure what kind of Android project he wanted to work on either so I bounced the idea off him and then we started hacking up some unit tests. My TDD process is pretty weak, and it was great working with someone who approached the problem from a test driven perspective. What I really liked about this was we were able to make API decisions right away. How do we want to get objects from the database? How do we want to interact with them? How would we create a table? I’ve read Becks’ book on TDD but have always found it tough to apply it when I’m actually working on something.

As for the project we worked on; it’s called velvet and the goal is to make working with databases on Android suck less. We haven’t really got much working with it yet, but the goal will be to have a simple data access layer, migrations and easy access to database cursors for presenting data in listviews and such. I’d have to say working with any kind of structured data with SQLite on Android requires far too much work already, wastes time and is often error prone.

So let’s say you have an application where you need to store the users password. Perhaps it’s a configuration setting that they need to use to log into some service you use or have created. The easiest (and most insecure) way to store the password would be to use the SharedPreferences for your application.

So in our preference XML we have an EditTextPreference which will be used to store the password. Though, we need to do a few things first otherwise the password will be plainly visible and there is the chance that the password might get saved in the auto-complete for the keyboard (SwiftKey is particularly bad for this).

For sake of argument, lets say our preferences xml is called “preferences.xml” and the key for the password is “password”.

What you will need to do is the following

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceClickListener;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MyPreferenceActivity extends PreferenceActivity implements OnPreferenceClickListener {
    private Preference passwordPref;

    public void onCreate(Bundle icicle){
        super.onCreate(icicle);
        addPreferences(R.xml.preferences);

        passwordPref = findPreference("password");
        passwordPref.setOnPreferenceClickListener(this);
    }

    public boolean onPreferenceClick(Preference preference){
        if(preference.getKey().equals("password")){
            EditTextPreference pref = (EditTextPreference) preference;
            EditText field = pref.getEditText();
            // This informs the keyboard not to show up the autocomplete.
            // Ensure that you have set this input type, otherwise users
            // may complain that your application is saving their passwords.
            field.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
            // This gives us the masking that you see in your password fields
            field.setTransformationMethod(new PasswordTransformationMethod());
        }
        // We still return false so that the system will handle everything else.
        // We just needed to ensure that if this preference is the password pref
        // that it's properly protected from prying eyes.
        return false;
    }
}

And there you have it. With this in place, entering password with the on-screen keyboard won’t show any text or save it.

As I mentioned earlier, this doesn’t save the passwords safely to the device. On a normal device this isn’t that much of a concern, though you should probably inform your user that the passwords are not encrypted. This issue becomes a bit more serious if there is malicious software on a device that is also rooted, since the naughty app could scrape through all the data directories looking for usernames and passwords stored in preference files.

I’m going to be available for employment within the near future. If you are interested in any skills I have to offer or feel that I may be a good fit on your team, please feel free to contact me.

I have a resume up on StackOverflow where you can get more information about what skills I have and to learn a bit more about me if you’d like.

So I’m doing some extremely simple operations here which requires a number that is between 0 and 9. If I am looking to decrement the number I want to ensure that I wrap around properly. The way I do this is by:

/**
 * Takes in a number between 0 and 9 and
 * ensures that the result is still a number
 * that is within that range.
 */
int decreaseValue(int value){
    int result = (value &mdash; 1) % 10;
        System.out.println("Result is: " + result);
    return result;
}

// This is just for demonstrations sake
// >> decreaseValue(0);
// "Result is: -1"

Now trying to be a good programmer, I’ve written up some unit tests that test code that essentially does this. Unfortunately, my code is stuck in an infinite loop. This makes absolutely no sense and I wanted to verify that I don’t fail at math as hard as I think I am so I pulled out my python interpreter and did essentially the same thing.

>>> def decreaseValue(value):
...     result = (value &mdash; 1) % 10
...     print "Result is: %d" % result
...     return result
...
>>> decreaseValue(0)
Result is: 9
9

Now the environment I’m running this code under is the Android 2.2 Simulator. I haven’t tried it on any devices yet, I’d just like to know if anyone else has had this issue or if I am indeed horrible at math and that is why my code isn’t working.

Edit:
It’s more of a misunderstanding of how the modulus operator operates in a Java environment. It’s very odd, and can catch you off guard.

So, the 26th of October has come and gone, and I’d just like to talk about my experience at AndroidTO. Before I start though, I’d just like to say I had a great time meeting with everyone and there is a very good chance I don’t remember your name. I’m not really a name person but if I see you again in public will probably recognize you, if not don’t be afraid to stop me and say hi.

The event itself was really well organized, and Puleen did a great job on keeping me on my toes (which I assume he did with the rest of the presenters as well). He’s a pretty persistent guy, but it always kept my presentation at the front of my mind.

The event ran very smoothly, besides a few technical hiccups such as the wireless; which honestly always happens at conferences. The choice of venue was really interesting; when I first heard that it was at the Polish Combattants Hall was thrown off a tad. This really wasn’t that big of a deal though, because it was right along a bunch of major TTC lines so getting there wasn’t a problem at all.

I was also really impressed with the androidTO app that was done by the great guys at http://mobicartel.com/. I was quite surprised at all the stuff they had done with making it a very polished Android application. From what I saw with Matt and Greg they are a great team, and I look forward to seeing what else they come up with in the future.

From what I’ve read around Twitter and from a few blogs, some of the presentations were a bit over peoples heads. They were pretty technical, especially the one by Manfred about the crazy stuff you can do with maven. Though, as a developer who’s been working with Android for several months now, I found the things he was talking about very intriguing. The tools he mentioned like Robotium and Roboguice look like amazing technologies that people should start looking into. If it were not for presentations such as Manfred’s I would’ve never heard about these tools, and that’s exactly what conferences like these are there for. Hopefully the things that were discussed will save everyone time from looking for these tools, especially when they don’t know what exactly to look for.

It was also nice to have seen Carmen going around taking photos of the event. I am not too sure if she was the official photographer, but it was awesome to see what she was doing. I brought my girlfriends point and shoot with me, but didn’t really want to disrupt some awesome conversations I was having with a lot of the people there. In case the organizers didn’t know, I’m also an amateur (read: wannabe) photographer and would totally be willing to go around an event in the future to take a bunch of shots at the next big Android thing going on. I also feel have some official photographers would help because then we would know in advance where to go to see all the pictures that were taken from the event.

The post event meetup was probably my favourite part of the event. This is always where everyone gets to actually learn more about people since there is actually time. There was of course even more great conversations that were going on, we got to talk about the technology even more as well as just getting to know each other more. I also found it great because I still find it difficult to tell how to know how someone is as a person, especially when most of the conversation I’ve gotten from them was on Twitter, where 2’s u’s and other various tragedies of the new millenium are required to actually say something.

I hope that everyone enjoyed my presentation, and I’ve encouraged you to begin using SQLite in your own Android projects as well. I was a bit nervous while I was up there, especially when my “Oh Shit” moment happened because I had forgotten to turn the wireless on my Macbook back on. Let me know what you liked, and how I could make the presentation better. I really love teaching people, and the only way I will know if what I’m teaching was good or not is if you let me know. Either send me an email, tweet or simply add a comment to this post. Also feel free to grab the code for use in your own projects. I warn you, the code does have it’s issues, and if you add some patches or clean some stuff up, feel free to send me the patch or or a pull request and I’ll be sure to bring it in.

I would like also like to thank my buddy Chris Millward for letting me crash at his place for my time down in Toronto for this conference. It was great to meet up with you again and talk about work, tech and everything else!

© 2011 Christopher Saunders Suffusion theme by Sayontan Sinha