Stories about Software


Adding a Google Map to Android Application

I’m documenting here my first successful crack at adding a google map to an android application. Below are the steps I followed, with prerequisite steps of having the Android SDK and Eclipse installed, and being all set up for Android development (documented here).

  1. Created a new Android project
  2. Navigated to Help->Install New Software in Eclispe.
  3. Added a new source with URL http://dl.google.com/eclipse/plugin/3.7
  4. Selected all possible options (why not, right?) to have access to the google API in general.
  5. This install took about 5 minutes, all told, and I had to restart Eclipse
  6. In my new project, I navigated to project properties and went to Android, where I selected (the newly available) “Google APIs”
  7. From here, I got excited and ran my project, and was treated to a heaping helping of fail in the form of an error message saying that I needed API version 9 and my device was running API version 8 (Android 2.2.1). I fixed this by opening the manifest and changing the uses-sdk tag’s android:minSdkVersion to 8. Then when I ran, I had hello world on my phone. (Later, when all was working, I just deleted this line altogether, which eliminated an annoying build warning)
  8. With that in place, I added the node

    to my application node in the same manifest XML file.

  9. Then, as I discovered in an earlier post, I had to add
  10. From there, I followed the steps in this tutorial, starting at number 4.
  11. One thing to watch for in the tutorial is that you should add the lines about the map view after all boilerplate code already in onCreate or mapView will be set null and you’ll dereference it.

With all of this, if you ignore the bit about the API key, what you’ll wind up with is a map with no overlay on your phone. That is, it looks like everything is normal, including zoom icons, but the map hasn’t loaded yet. This was the state I found myself in when I decided that I’d take the last step and get the API key. This was not at all trivial.

I understand that if you’re familiar with the concept of signing software for distribution in app market, this probably makes sense. But, if this isn’t something you’ve been doing, it comes straight out of left field and, what’s more, there was no real place where how to do this was described in any detail. So, I’ll offer that here.

  1. Navigate to your JAVA_HOME bin folder (wherever your java and javac executables are)
  2. Run the command
    keytool -v -list {keystore}

    . The -v is important because this gives yo all the fingerprints (the default is SHA1, which won’t help you in the next step — you want MD5). The keystore is going to be debug.keystore, which is what your device uses for signing when you’re developing and not releasing. For me, this was located in C:\documents and settings\erik\.android on this win XP machine (YMMV with the directory)

  3. What you’ve done here is generated a fingerprint for the developer debug keystore that Eclipse automatically uses. This is fine until you want to deploy the app to an app store, at which time you’ll have to jump through a few more hoops.
  4. Take the key that this spits out and copy it (right click and select “mark” in cmd window), and paste it into the “my certificate’s MD5 fingerprint” text box here: http://code.google.com/android/maps-api-signup.html
  5. This will give you both your fingerprint, and an example layout XML to use in your Android map project
  6. Copy this into your project’s layout, following the guide for naming the attribute that contains the key. (That is, find your layout’s com.google.android.maps.MapView node and set its android:apiKey attribute to the same as the one on the page you’re looking at.
  7. Once you’ve got this, you can paste it into your map layout, run your app (phone or emulator) and get ready to start navigating to your heart’s content

After I went through all this, I found this clearly superior tutorial: http://mobiforge.com/developing/story/using-google-maps-android. This is really great for getting started, complete with code samples and starting as simple as possible.


Compiling XML! (Not really)

So, here’s another one filed in the “hope this saves someone some grief” category. I was cruising along with my home automation ‘droid app, setting my layouts and wiring up my button click handlers, when all of a sudden, I was getting weird build errors about. I couldn’t run or even build. When I tried to build, I got messages about different things being redefined in my main XML layout file. This was strange, since I hadn’t edited it directly, but was using the graphical layout tool.

As I inspected the errors more closely, I began to understand that there was apparently some rogue XML somewhere. A bug in Eclipse? With the Android SDK plugin? Had I been hacked by someone with a very strange set of motives? I opened up my layout folder and this is what I saw:


After some googling around and experimentation, I discovered that this file is generated if you run with the Play icon and the XML file open as your selected window in the editor. Perhaps that’s something that Eclipse users are used to, but coming from a pretty solid couple of years of Visual Studio, this had me mystified. So, lesson learned. Don’t run if you have XML open in Eclipse (or anything else you don’t want slapped with a .out between filename and extension and apparently included in compilation.

Cheers 🙂


Android: Let There Be Internet!

I’ve been a little lax in documenting my experience as a neophyte Android developer, and for that I apologize. Tonight, I have a quick entry that will hopefully save you some time.

I’m working on an open source home automation server. I’ve had a prototype functional for a couple of years now that runs as a web server in apache, Java-based, and controls the lights through a web interface front end and a low level backend that interfaces with the house’s electrical system. I control this through any computer/phone/ipod/wii/etc that’s hooked to my home wifi, using the browser.

Recently, I’ve wet my beak a little with Android development, out of curiosity, and so my mission tonight was to take the layout I’d been working on and get it to, you know, actually do something. So, the simplest thing for me to do was have the app reproduce the POST request sent by the browsers to get the desired result. Here is the code I slapped together for this:

final Button myButton = (Button) findViewById(R.id.breakfastNookButton);
        myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	HttpClient myClient = new DefaultHttpClient();
                HttpPost myPost = new HttpPost("you-get-the-idea");

                try {

                } catch (ClientProtocolException e) {
                } catch (IOException e) {

Not the prettiest thing I’ve ever written, but this is a throw-away prototype to prove the concept (though I’m going to refactor tomorrow – I can’t help myself, prototype or not).

So, I fired it up and nothing happened. I checked out the stack trace and was getting an UnknownHostExeption, which didn’t make sense to me, since I was using the home automation server’s IP address. I used the browser on my phone, and I could turn the light off. I googled around a bit and found a bunch of information about things that can go wrong with the emulator, but I’m debugging right on my phone since the Emulator is painfully slow.

Finally, I stumbled across a suggestion and got it right through some experimentation. I needed to give the app permission to use the internet! So, I updated my manifest to the following:


Important line is the “uses-permissions” node, and, viola, let there be dark! My light turned off. Hope that helps someone out there struggling to understand the UnknownHostException for a known host.

(Note, the node level in the XML file is important — it must be a child of manifest, NOT application).


Re-Learning Eclipse

Recognizing and Understanding My Irritability

I’ve been dabbling off and on in Android development lately. For a long time, I used Eclipse on a regular basis and got to know the ins and outs of it quite well, but as a look at my tag cluster will tell you, Visual Studio has been my main IDE over the last couple of years. The result is that my Eclipse skills are getting as rusty as my Spanish (fluent enough to read novels when I was 20, rusty enough to struggle reading the blurbs about movies on Spanish language channels now). So, picking it back up is an experience in annoyance. I now expect everything to work the way Visual Studio does. That’s kind of ironic since when I first switched over to Visual Studio, I downloaded this plugin, called “AsEclipse.”

As a user, I’m entirely justified. Jakob Nielsen describes the effect of user annoyance.

Annoyances matter, because they compound. If the offending state-field drop-down were a site’s only usability violation, I’d happily award the site a gold star for great design. But sites invariably have a multitude of other annoyances, each of which delays users, causes small errors, or results in other unpleasant experiences.

Even if no single annoyance stops users in their tracks or makes them leave the site, the combined negative impact of the annoyances will make users feel less satisfied. Next time they have business to conduct, users are more likely to go to other sites that make them feel better.

He’s talking about E-commerce websites specifically, but I believe the same wisdom applies to any application. User annoyances add up. If you’re a Windows user used to Mac or vice-versa, weird little things happen that run counter to what you expect. The thing that you think closes a window toggles or maximizes it. The hot-key that you punch has no effect. You’re pissed off before you even realize it. Same thing happens with competing IDEs.

Getting Zen

So, rather than let myself get annoyed, I’m going to document some things here to help me remember how to do things in Eclipse that I take for granted in Visual Studio — to retrain my fingers and brain a bit. I’m going to be keeping this page open as I work, and I’m hoping others find it useful as well. So, without further ado, here is a list of shortcuts/techniques:

  • Switch between files (ctrl-tab in VS): Ctrl-F6 or Alt-Arrow. (Note, this doesn’t rotate through like VS, but switches between most recent, ala Notepad++
  • Resolve reference (Ctrl-Shift-Period in VS): Ctrl-Shift-M
  • Camel-Case Tabbing: Ctrl-Alt-Arrow (with CodeRush anyway): Ctrl-Arrow.
  • Build (Ctrl-Shift-B in VS): Ctrl-B
  • Auto-comment method (/// and then space in VS): Alt-Shift-J
  • Comment block (Select and press “/” with VS/CodeRush): Select and press Ctrl-/.

I’ll probably come back and add to this list as time goes on, but I figured I’d get it started. Hopefully you find it helpful too. Also, please, by all means, add any additional ones to the comments here, and I’ll add them to this list as well.


Getting Started With Android Development

I posted some time back about developing for Android and getting set up with the Android SDK, the Eclipse plugin, and all that. For the last six months, I haven’t really had time to get back to that. But now I’m starting to delve into Android development in earnest, so this (and potentially other upcoming posts) is going to be about my experience starting to write an Android application. I think I can offer some interesting perspective here. I am an experienced software developer with breadth of experience as well as depth in some technologies, but I am completely new to Android SDK. Hopefully, my experiences and overcome frustrations can help people in a similar position. This also means that you’d be learning along with me–it’s entirely possible that some of the things I post may be wrong, incomplete, or misguided in the beginning.

This post kind of assumes that your knowledge is like mine. I have a good, if a bit rusty from a year and a half of disuse, working knowledge of Eclipse and J2EE development therein. I’m also familiar with web development and WPF, so the concept of object-oriented plumbing code with a declarative markup layout for the view is quite familiar to me.

Notes about Setup

Just as a bit of background, I do have some things set up that I’m not going to bother going through in this particular post. I have Eclipse installed and configured, running on a Windows XP Pro machine. I also have, at my disposal, a Samsung Epic 4G running Android 2.3. (I forget the name of the food that accompanies this version, and, to be perfectly honest, something strikes me as sort of lame about naming your releases after desserts. Different strokes, I guess.) I also have installed ADB and the drivers necessary for connecting my computer to my phone. And finally, I have the Android virtual machine emulator, though I think that just comes with the Eclipse SDK plugin or something. I don’t recall having to do anything to get that going.

Creating a new Android project

One of the things that’s difficult when you’re new to some kind of development framework is separating what actually matters to your basic activities and what doesn’t. Any framework-oriented development, in contrast to, say, writing a C file and compiling it from the command line with GCC, dumps a lot of boilerplate on you. It’s hard to sort out what actually matters at first, especially if your “training” consists of internet tutorials and trial and error. So I’m going to note here what actually turned out to matter in creating a small, functional app, and what didn’t so far.

When you create a new project, you get a “SRC” folder that will contain your Java classes. This is where you’re going to put a class that inherits from “Activity” in order to actually have an application. I’ll get to activities momentarily. There’s also a “Gen” folder that contains auto-generated Java files. This is not important to worry about. Also not important so far are the “assets” folder and the Android2.1-update1 folder containing the Android jar. (Clearly this is quite important from a logistical perspective, as the Android library is necessary to develop Android apps, but it makes no difference to what you’re actually doing.)

The res folder is where things get a little interesting. This is where all of the view layer stuff goes on. So if you’re a J2EE web developer, this is the equivalent of the folder with your JSPs. If you’re a WPF/Silverlight developer, this is the equivalent of a folder containing your XAML. I haven’t altered the given structure, and I would’t suggest doing it. The layout subfolder is probably the most important, as this is where the actual view files defining UI components in XML go. In other subfolders, you’ll find places where your icon is defined and where there are centralized definitions for all display strings and attributes. (I haven’t figured out why it’s necessary to have some global cache of strings somewhere. Perhaps this is to take advantage of some kind of localization/globalization paradigm in Android, meaning you don’t have to translate yourself for multi-lingual support. Or maybe I’m just naively optimistic.)

The other thing of interest is the AndroidManifest.xml. This contains some application-wide settings that look important, like your application’s name and whatnot. The only thing that I’ve bothered so far to look at in here is the ability to add an attribute to application called “android:debuggable=”true”. Apparently, that’s needed to test out your deployable on your device. I haven’t actually verified that by getting rid of the attribute, but I seem to recall reading that on the Android Dev forum.

Those are all of the basic components that you’ll be given. The way that Android development goes on the whole is that it is defined in terms of “Activities.” An activity can loosely be thought of as a “screen.” That is, a very basic application will (probably, unless it’s purely a background service) consist of one activity, but a more complex one is going to consist of several and perhaps other application components like services or content providers. Each activity that you define in your application will require a class that extends the “Activity” class and overrides, at least, the “OnCreate(Bundle)” method. This is what you must supply to have a functioning application–at the very least, you must set your activity’s content.

To summarize, what you’re going to need to look at in order to create a hello world type of app on your phone is the Java file you’re given that inherits from activity, the main.xml file in layout, and the manifest. This provides everything you need to build and deploy your app. Now, the interesting question becomes “deploy it to where?”

Deployment – Emulator and Phone

I quickly learned that the device emulator is very, very slow. It takes minutes to load, boot, install your deployable in the virtual environment. Now, don’t get me wrong, the VM is cool, but that’s fairly annoying because we’re not talking about a one-time overhead and quick deployment from there. It’s minutes every time.

Until they optimize that sucker a little, I’d suggest using your phone (or Android tablet, if applicable, but I’m only going to talk about the phone) if it’s even remotely convenient and assuming that you have one. As I discovered, when you run your Eclipse project as an Android app, assuming you’ve set everything up right, the time between clicking “run” and seeing it on your phone is a couple of seconds. This is a huge productivity improvement and I didn’t look back once I started doing this.

Well, let me qualify that slightly. The first time I did it, it was great. The second time I deployed, I got a series of error messages and a pop up asking me to pick which deployment environment I wanted: the emulator or my phone. I wanted my phone, but it was always shown as “offline.” To counter this problem, I discovered it was necessary to go on the device itself and, under “Settings,” set it never to sleep when connected. Apparently, the phone going to sleep sends the ADB driver into quite a tizzy. If you have hit this, just changing the setting on your phone won’t do the trick. You’ll need to go into the platform-tools directory of wherever you installed the Anrdroid SDK and run “adb.exe kill-server” followed by “adb.exe start-server”. For you web devs out there, think of this as clicking on the little tomcat dude with the stop and then the little tomcat dude. 🙂

Now with this set up, you should be able to repeatedly deploy, and it’s really quite impressive how fast this is considering that you’re pushing a package to another device. It’s honestly not noticeably different than building and running a desktop app. The server kill and start trick is useful to remember because there is occasional weirdness with the deployment. I should also mention a couple of other things that didn’t trip me up, but that was because I read about them in advance. To debug on your phone, the phone’s development settings need to be configured for it. In your phone’s settings, under “Applications,” you should check “Allow Installation of Non-Market Applications” and, under “Debugging,” check “USB Debugging”. (On my phone, this is also where you find “Stay Awake,” which caused the problem I mentioned earlier, but YMMV.)

Changing the Icon

One of the first things that you’ll notice is that your “Hello World” or whatever you’re doing deploys as the default little green Anrdoid guy. Personally, when I’m getting acquainted with something new, I like to learn about it by changing the most obvious and visible things, so very quickly I decided to see how changing the icon worked. In your “res” folder, there are three folders: “drawable-hdpi”, “drawable-ldpi”, and “drawable-mdpi”. A little googling showed me that these correspond to high, low, and medium resolution phones. Since Android developers, unlike their iOS counterparts, need to worry about multi-device support, they need to have a vehicle for providing different graphics for different phones.

However, at this point, I wouldn’t (and didn’t) worry about this. I took an image that I wanted to try out as my icon and put it into these folders, overwriting the default. Then, I built and I got some error about the image not being a PNG. Apparently, just renaming a JPG “whatever.png” isn’t enough to trick the SDK, so I opened it in MS Paint and did a “Save As,” selecting file type PNG. This did the trick. As best I can tell, your icon will be capped in size, so it’s better to err on the side of making it slightly too big.

Changing the App Name

When I set all this up last winter, I followed a tutorial that had me build an app called “SayHi”. I was trying to prove the concept of taking an Eclipse project and getting it to run something, anything, on my phone. As such, when I picked it back up and started playing with it, the app was still called “SayHi”. However, I don’t want this app to say hi. It’s actually going to be used to turn lights on and off in my house in conjunction with my home automation. So, I’d like to call it something catchy–something imaginative, you know, like “Light Controller.”

This is actually refreshingly easy for someone who has been working with Visual Studio and Clear Case–a tandem that makes renaming anything about as convenient as a trip to the DMV. Under “res->values,” open the “strings.xml” file. You’ll have tabs at the bottom to view this as raw XML or as a “Resources” file. Either way, the effect is the same. You’ll change the “app_name” string to the value that you want, and that’s it. On the next deployment to your phone, you’ll see your app’s new name. Pretty cool, huh? Two easy changes without any code or having an app that actually does anything, and it at least looks like a real app until you open it.

At this point, I should probably mention something that may not be familiar to you if you’re just getting started. In Eclipse and with the Android SDK, you have various options for how you want to view the XML files. The manifest one seems to have a lot of options. The strings one has the XML versus resource choice. From what I recall, this is a feature of Eclipse in general–I believe plugins can supply their own view of various file extensions. If you want to see what all is theoretically available for any file, XML or not, right click on it and expand “Open With.” That’ll show you all the options. It’s important to remember that even though you may get defaulted to some kind of higher level, GUI-driven editor, you always have the raw text at your disposal. Having said that, however, my experience editing layouts taught me that, for beginners, it’s a lot easier to use the SDK’s layout editor. You’ll save yourself some headaches.

This post has gotten pretty long, so I’ll save my adventures with layouts and GUI components until next post.