Android code sample

I wanted to try some smart phone development. I started with Mac OsX in a VirtualBox got the Os installed on the virtual machine, but it wouldn’t boot for me after install. As I was fiddling with that on my Windows box to do iPhone development I thought this is way harder than it’s supposed to be.

Then I thought let’s see how this compares to doing Android development. Went to the Android SDK site and got the SDK which integrates with Eclipse very easily. The installs are just a few clicks of a button and your all set. Of course they have a Hello world sample that you will have running in Android emulator in matter of minutes. The install instructions show how to setup different devices under the emulator etc.

Now what about something more than just Hello world, the SDK comes bundled with all kind of samples, both controls and graphics along with more elaborate Google maps location based samples. It has plenty of stuff to get you going. The great thing is that the code is plain old Java so if you have done any Java or C# development you will feel right at home.

I wanted to do something basic before going into any real development. My idea is to create a simple calculator to calculate handicap score. I used to play pool and we would have a simple handicap system that needed to be referenced to calculate the race between two people that have been matched up.

When Android project is created in Eclipse it will create a bunch of files, resources, manifest, etc. and the main Activity class. The Hello world sample creates control dynamically in code but that can be hard to maintain when your project increases in size. The way to do it is to declare the controls in a XML resource file and then reference it in code. I didn’t see a editor to handle the controls visually but I’m sure there are some out there.

For a simple app the XML is found under res/layout/main.xml in my case it will look like this.

<?xml version=“1.0” encoding=“utf-8”?>
<RelativeLayout xmlns:android=“”

        android:text=“Handicap Player1:”/>


        android:text=“Handicap Player2:”/>


        android:text=“Calculate” />

        android:text=“Number of games Player1 must win:”/>


        android:text=“Number of games Player2 must win:”/>



Things to notice are the id’s of the controls they need to be unique and how the layout is done for each control you specify where it should show up relative to other controls. That way the manager rendering your view can order them and it will look pretty good.

As I mentioned before the code is in java.

import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

public class helloActivity extends Activity implements OnClickListener

        /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState)
        // The usual
        // Wire up click event
        Button button = (Button)findViewById(;
    // Implement the OnClickListener callback
    public void onClick(View v)
        // Input from user
        String sPlayer1 = ((EditText)this.findViewById(;
        String sPlayer2 = ((EditText)this.findViewById(;
        // Turn into doubles
        double[] players = {0,0};
        players[0] = Double.parseDouble( sPlayer1 );
        players[1] = Double.parseDouble( sPlayer2 );
        // Calculate
        calculate( players );
        // Set the results
        ((EditText)this.findViewById( )).setText( “” + (int)players[0] );
        ((EditText)this.findViewById( )).setText( “” + (int)players[1] );
    // Calculates handicap
    private static void calculate( double[] pdaPlayers )
        // STRONGER is lower handicap
        // See who is better rated coming in,
        boolean bStrongerFirst =  pdaPlayers[0] < pdaPlayers[1];
        // Holds results
        double strong_race, weak_race;

        if( bStrongerFirst )
            // What’s the race
            weak_race = Math.max(2, 6Math.floor( pdaPlayers[1] ));
            strong_race = weak_race + Math.round( pdaPlayers[1] – pdaPlayers[0] );
            // set the slots before returning
            pdaPlayers[0] = strong_race;
            pdaPlayers[1] = weak_race;
            // What’s the race
            weak_race = Math.max(2, 6Math.floor( pdaPlayers[0] ));
            strong_race = weak_race + Math.round( pdaPlayers[0] – pdaPlayers[1] );
            //  Set the slots before returning
            pdaPlayers[0] = weak_race;
            pdaPlayers[1] = strong_race;

}  // EOC

The onCreate function is the main function of the activity, to get button click event it will be setup there. The rest is straight forward and activated when the user clicks the button. The controls are addressed by which is the resource id’s given to each control in the layout XML. The R mapping is created when the project is compiled. For this simple sample, the user input is retrieved and used to calculate handicap which is then presented back to the user in controls below.

The app running in Android emulator

I just didn’t find the visual editor, it’s there in Eclipse it shows as tab when you open up the xml file. It’s very primitive one might be better off to use DroidDraw


  1. sk says:

    I’ve been thinking about this for awhile. Apple took their existing tools and
    language that were used to develop Mac OS apps and extended it to the phone. People not wanting to buy a new machine to do dev on (Mac Mini for $500) or to learn a new language (Objective C) start complaining that Apple is being restrictive. “I can’t build iPhone apps in Ruby on Ubuntu? You suck!”

    This begs the question of “Why should Apple be responsible for providing tools on other OSes or other language bindings?” In fact it’s in their best interest not to. It means more people use Macs. Before .NET, Microsoft Windows stuff had a choice of C++ or VB and not much else. Java was just starting and there weren’t very good tools. More often than not, the case of other tools and other language bindings come from outside of the original company. It is through this work of other companies, companies that aren’t OS suppliers, that we have gotten this dearth of language choices on all these platforms. You want to write Windows apps on Linux? Don’t ask Microsoft, but rather the Mono project. OS suppliers target their OS. They want you to use it, not something else.

    One could say that Apple is behind the times since Microsoft now supports
    multiple languages to write OS specific applications. Then again, they probably don’t care. I think their main objective would be to get more users on their platform. Given that they have a market share around 5% that makes complete sense.

    So, is Apple restrictive in that I have to use their tools? Yes. Does that
    bother me as a developer? A little bit, but instead of looking at it that way, I look at as an opportunity to learn a new language and a new set of tools which will hopefully make me a better, more rounded developer.

    Android, being Java based can rope in the millions of existing Java developers. With Google, they are trying to sell you ads. This is why they give all their stuff away. The more people that use it, the more ads they can sell. As one comment I read on the net said “If you are not paying for it, you’re not the customer; you’re the product being sold.”

    With Apple, it is hardware, or their complete user experience that they are

    iPhone dev on Windows…I came up with these. You can do a google search and find others presumably.

  2. orn says:

    Yea true, but how good is Mac mini for development, does it have enough juice ? I would think you needed something more powerful. My approach is usually, try the trial product see if I like it, if I want to use it buy it. So naturally I thought run it on my machine that has plenty of power even when running in VM, buy the OsX of Ebay for $50 and take it from there. Now obviously if I start selling products in the app store left and right I would buy a Mac and take it to the next level.

    It’s not like I haven’t come against this before, couple of weeks ago I wanted to do Adobe Air development. And since they have Eclipse / Java tools I decided to develop on my Ubuntu box. Guess what, they only support the dev tools on Mac and Windows and they don’t have install for Linux, go figure. At least they give you 30 day trial so you can see if this is something you want to use before you buy it.

    I like to differ on the tools before .Net statement, you never saw Delphi ? It was way better than VC++ or VB at the time. Guess who MS got involved in .net C# I did actually blog about that before ( ) I remember using Borland C++ as well, but I do agree on the fact that good tools were scarce on Windows.

    It’s funny how Novell is doing Mono isn’t it, it didn’t start out as Novell project, they got involved before ver 1.0 was ready if I remember correctly. Once Novell got involved Mono starting moving quicker than before, a good deal. And now I just read that they are going to create MonoDroid as well, which in turn means you can use the Mono tools to target both iPhone and Android, nice ! ( ) I just say thank god Microsoft wised up and started making things semi open with .Net

    I have nothing against using Apple tools, I’m told they are pretty good. I was looking at it the same way, get involved in something new that in return makes me more rounded developer. New language more fun and different perspective. However if that means in order to play with stuff that I need to buy a Mac, probably at least $1000 for a machine worthy of development then I’m really hesitant.

    True enough Google has an angle, that is the business they are in. It’s scary how much information they have on their users.

  3. sk says:

    Ack! I forgot about Delphi. I used Borland stuff back in the day. I even played around with their OWL C++ lib for Windows dev.

    I understand completely where you are coming from. The big issue is that Apple doesn’t like their OS to be used on anything but their machines. Not many companies do that anymore, except maybe the big Unix shops (IBM & AIX, HP & HP UX, dunno about Sun). That is where people bristle. They are used to being able to install an OS anywhere. That gives you a bigger barrier to entry into that field.

  4. orn says:

    Yea it was the MFC vs OWL discussion back then. I never really used Borland C++ it was more just to test the waters, didn’t seem to work as well as the Ms stuff for me. But I LOVED Delphi, it kicked much butt.

    I think it’s the same with Sun / Solaris at least it used to be, they all tied the Os to the hardware.

Leave a Reply