Wednesday, March 10, 2010

Uri and Android 1.5

I came across an interesting Android bug the other day that deserves some mention.

I was creating an Intent, setting some data for it, then calling startActivity(). The data Uri was created via Uri.Builder. Let's say, for example, the Uri I wanted was "http://google.com". The code would look like thus:

Intent intent = new Intent(context, TestActivity.class);
Uri.Builder builder = new Uri.Builder();
builder.scheme("http");
builder.authority("google.com");
intent.setData(builder.build());
startActivity(intent);

This works in 1.6+. But an interesting thing happens if you try this in 1.5... it blows up in your face with NullPointerExceptions! To answer why, I ended up digging around previous versions of the android.net.Uri class. It turns out that, previous to 1.6, Uri expects you to fill out every part of the Uri - including the query parameters (parts following ?) as well as the fragment (part following #).

The fix is to add dummy parameters for the sake of Android 1.5:

Intent intent = new Intent(context, TestActivity.class);
Uri.Builder builder = new Uri.Builder();
builder.scheme("http");
builder.authority("google.com");
builder.appendQueryParameter("ignore", "ignore");
builder.fragment("ignore");
intent.setData(builder.build());
startActivity(intent);

This isn't a problem if you already are using all parts of a Uri, or if you only support Android 1.6+.