Android: Place Finder & Command Processor

Place Finder is a simple Android application which allows the user to input an address and see a map of the target area. It is composed of two screens

Main

Here we can see the main view with the menu displayed. Selecting ‘Find’ takes you to the geocoder activity.

Main

You can see that as the user types into the inputbox the list is updated.

This is a simple technology demo I put together as part of the process of learning the Android framework. Obviously on the phone you could just use the browser to go to Google maps and get the same result. Having said that, this application looks a lot simpler than it actually is. I have tried to give it a bit of polish so there is a ton of useful stuff going on under it’s seemingly bland exterior. Highlights are

You will find the code here.

Okay so lets get into it. First off the main Activity is pretty straightforward. I use a RelativeLayout to positions the items one after the other. Note the use of the gravity setting to pin the location label and zoom controls to the top and bottom of the screen as well as the ‘center_horizontal’ attribute to make sure they appear in the centre.

< ?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<textview android:id="@+id/location_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top|center_horizontal"
android:paddingBottom="4dip"
android:text="@string/current_location"
layout_alignTop="@id/main"/>

<com .google.android.maps.MapView
android:id="@+id/map_view"
android:apiKey="0CUuMSxY0DgY3neL24D9xMte0xIOxNo0cywRluw"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:layout_below="@id/location_name"/>

<linearlayout android:id="@+id/layout_zoom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="bottom|center_horizontal"/>

</relativelayout>

The apiKey value published here is the debug key and won’t work with a signed app so save yourself the hassle of trying it. I have no idea if this will work with anyone elses emulator setup but if it doesn’t follow the readme.txt in the bundled code.

The Activity ‘MapViewGeocodeActivity’ launches the Geocode view using the defined constant ‘REQUEST_GEOCODE_ACTIVITY’.

public void showGeocode()
{
// Get location value to pass to the geocoder (as a possible initial setting).
Intent geocodeIntent = new Intent().setClass(this, GeoCodeActivity.class);

// Make it a sub-activity so we know when it returns
startActivityForResult(geocodeIntent, REQUEST_GEOCODE_ACTIVITY);
}

The constant ‘REQUEST_GEOCODE_ACTIVITY’ is then tested for then the Geocode view exits and the ‘onActivityResult’ method is triggered.

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);

// The preferences returned if the request code is what we had given
// earlier in startSubActivity
if (requestCode == REQUEST_GEOCODE_ACTIVITY)
{
if (data!=null)
{
// Extract results
Bundle extras = data.getExtras();

String location = extras.getString(GeoCodeActivity.DATA_LOCATION);
double longitude = extras.getDouble(GeoCodeActivity.DATA_LONGITUDE);
double latitude  = extras.getDouble(GeoCodeActivity.DATA_LATITUDE);

// We're going to use the preference to store our settings.
Preferences preferences = Preferences.instance(this);
preferences.setLocation(location);
preferences.setLatitude(latitude);
preferences.setLongitude(longitude);
}
}
}

The result is extracted and passed to the Preferences mechanism where it is persisted. I have implemented a Preference singleton to hide the details of this. Note I am having to pass a reference to the main activity to the Preference instance singleton method. This is a bit unusual but this is needed to provide the Preferences with a context (as in Android context) reference.

The GeoCodeActivity class is a lot more interesting. It maintains a list of results, a geocoder component and a special list adapter which takes the results list of ‘Address’ objects and creates a description to display in the list rows.

// Empty list
list = new ArrayList<address>();

// Create geocoder
geocoder = new Geocoder(this);

// Results list adapter
adapter = new LocationListAdapter(this, list);

It also keeps a reference to a ‘GeoCodeCommand’ object. The ‘GeoCodeCommand’ class takes a text location description and updates the main list with the geocoder results (a list of Address objects funnily enough). In order not to bring the user interface to a halt this process is done in a background thread.

If you get the application running you will see that you can type as fast as you like and delete characters and the geocoder will always give timely results. How is this done? The technique is

The actual geocoding is done by a ‘GeoCodeCommand’ instance which has been submitted to the CommandProcessor. The CommandProcesser will spawn a background thread to issue the geocoding request. We keep a reference to the command so we can test it’s running status.

private void issueQuery(String text)
{
geocodeCommand = new GeoCodeCommand(text, adapter, list, geocoder);

Log.d("GeoCodeActivity", "issueQuery, "+text);

CommandProcessor.instance().add(geocodeCommand);
}

Command Processor

A Command Processor is a design pattern I came across a while back in this book. It is quite a well known pattern and is normally used to track operations which can then be undone by following the list of executed commands. It’s a nice way to abstract discrete operations and can be given a twist to act as a controller for queuing commands which may be marked for threading or not.

In the context of the Android framework I have been through the various permutations of creating a background thread. I ended up using the ‘UserTask’ class which is used in a few of the the apps-for-android examples. The problem was I didn’t really understand what was going on. The code is a bit dense and I felt a bit hemmed in by the use of generics for submitting parameters and getting a result back. Also, I reckon the best way to learn something it to try and write your own version so with that in mind I pored over the threading code and integrated it into the Command Processor pattern.

Main

This looks insanely over-engineered to do what I am using it for but what I am trying to achieve is a measure of control over the threading process. This gives us something where

So how does it hang together?

The two main classes which implement the Command Processor are Command and CommandProcessor.

The Command class implements a simple interface and is destined to be overridden.

public class Command implements Runnable
{
	private boolean threaded = false;

	private Status status = Status.PENDING;
	
	public Command(boolean threaded)
	{
		this.threaded = threaded;
	}

	/**
	 * Execute command.
	 * 
	 */
	public void run()
	{
		status = Status.RUNNING;
		
		execute();
		
		status = Status.FINISHED;
	}
  
	/**
	 * Override in subclasses. I have not made this abstract as it has it's uses like
	 * providing an empty command for signalling blocking queues.
	 * 
	 */
	public void execute()
	{
		// I can connect nothing with nothing.
	}

	/**
	 * Is command threaded.
	 *   
	 * @return threading flag.
	 */
	public boolean isThreaded()
	{
		return (threaded);
	}

	/**
	 * Return command state.
	 * 
	 * @return status
	 */
	public Status getStatus() 
	{
		return status;
	}

	/**
	 * Set run status.
	 * 
	 * @param status
	 */
	public void setStatus(Status status) 
	{
		this.status = status;
	}
	
	/**
	 * We introduce a method to return runnable interface. This is because subclasses may
	 * wrap this command and present a different runnable interface by overloading this 
	 * method.
	 * 
	 * @return Runnable interface
	 */
	public Runnable getRunnable()
	{
		return this;
	}
	
	/**
	 * Status of command.
	 * 
	 */
	public enum Status 
	{
		PENDING,
		RUNNING,
		FINISHED;
	}	
}

This sub-classes from Runnable so we can execute this type of object in a thread. The base class version of the run method sets status and calls the main override for subclasses ‘execute’. Notice the method ‘getRunnable’. In the base class this returns a reference to this but in our UICommand subclass we are going to return something different. I will come to that in a moment.

The CommandProcessor is simply a Runnable object which implements a blocking queue of commands. When a command is added to the queue it is taken off and examined to see if it should be run in it’s own thread or not.

/**
* Runs in it's own thread.
* 
*/
public void run()
{
    process();
}
    
/**
 * Process pending commands by removing them from pending list and placing them on executable list.
 *    
 */
public void process()
{
    running = true;
    try
    {
        while (running)    // keep going
        {
            // Block on waiting for command 
            Command command = commandsPending.take();

            if (command!=null)
            {
                if (command.isThreaded())
	         {
	                // command executes in its own thread
	                ThreadManager.instance().add(command.getRunnable());
	         }
	         else
	         {
	             	// Run the command directly without spinning a thread.
	               	command.getRunnable().run();
	         }
            }
        } 
    }
    catch (IllegalThreadStateException  e)
    {
        // Thread stopped
        running = false;
    } 
    catch (InterruptedException e) 
    {
        // Thread stopped
        running = false;
    }
    catch (Throwable t)
    {
        running = false;
        throw new RuntimeException("An error occured while executing command", t);
    }
}

The CommandProcessor thread is stopped by setting the running flag to false, clearing the pending queue and then adding a dummy command to unblock the queue ‘take’ method. This seems the simplest way to do this. I could have implemented something more elegant looking but what would be the point?

public synchronized void stop() 
{
	this.running = false;
		
	// Clear queue and add empty command to indicate end
	commandsPending.clear();
	commandsPending.add(new Command(false));
}

Man, this is turning into a bit of a marathon post. Still with me? The UICommand is where we leave the JDK behind and start into Android territory. The UICommand sub-classes the Command object but then does something odd. It wraps itself inside an Android ‘FutureTask’ instance (in this case I have subclassed FutureTask into UITask). This is an object which is also Runnable and it is this which gets threaded. The getRunnable method is overridden and the FutureTask interface is returned instead. Here’s some of the relevant bits of the class.

public class UICommand extends Command 
{
    private static final int MESSAGE_POST_START = 0x1;
    private static final int MESSAGE_POST_PROGRESS = 0x2;
    private static final int MESSAGE_POST_END = 0x3;
    private static final int MESSAGE_POST_CANCELLED = 0x4;

    private static final InternalHandler handler = new InternalHandler();

    // The runnable component is wrapped in a FutureTask.
    private UITask task = new UITask(this);
    
	public UICommand(boolean threaded) 
	{
		super(threaded);
	}

	/**
	 * Cancel the task and signal cancelled state.
	 * 
	 */
	public void cancel()
	{
		task.cancel(true);
		
		publishCancelled();
	}
	
	/**
	 * This saves us having to provide a reference to the composite task.
	 * 
	 * @return cancelled state.
	 */
	public boolean isCancelled()
	{
		return task.isCancelled();
	}
	
	/**
	 * This is overridden version of the main runnable method. 
	 * 
	 * Note the calls to signal the start and end of the task.
	 * 
	 */
	@Override
	public void run() 
	{
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

		publishStart();
		
		execute();
		
		publishEnd();
	}

	/**
	 * Because we are wrapping the command runnable in a FutureTask we present that
	 * interface to the the execution mechanism.
	 * 
	 * @return Runnable interface
	 */
	@Override
	public Runnable getRunnable()
	{
		return task;
	}
}

Notice we are completely overriding the base ‘run’ method and implementing a new one which signals the start and end of the execute with the ‘publish’ calls (more on this further on).

The FutureTask presents an interface which we wrap in our UICommand. It has a run method and importantly a ‘cancel’ method which can pull down the running thread and set a ‘cancelled’ status which our overridden ‘execute’ method can query if it is doing something in a loop.

This application doesn’t really give a good example of this but say you are parsing a large piece of XML. In you parsing loop you can query ‘isCancelled’ and stop if it is true. I have used this mechanism to solve a problem in my Simple Weather application where the background process was holding on to resources a tad too long.

The other major thing to note about the UICommand class is the private class ‘InternalHandler’

    protected final void publishStart()
    {
        setStatus(Status.RUNNING);
        handler.obtainMessage(MESSAGE_POST_START, new CommandResult(this)).sendToTarget();
    }
    
    protected final void publishProgress()
    {
        handler.obtainMessage(MESSAGE_POST_PROGRESS, new CommandResult(this)).sendToTarget();
    }
    
    protected final void publishEnd()
    {
        setStatus(Status.FINISHED);
		
        handler.obtainMessage(MESSAGE_POST_END, new CommandResult(this)).sendToTarget();
    }

    protected final void publishCancelled()
    {
        handler.obtainMessage(MESSAGE_POST_CANCELLED, new CommandResult(this)).sendToTarget();
    }
    
    // -------------------------------------------------------------------
    // Override these in subclasses to handle situation signalled from thread
    // -------------------------------------------------------------------
    
    public void onPreExecute()
    {
    	Log.d("onPreExecute", "called");
    }
    
    public void onProgressUpdate()
    {
    	Log.d("onProgressUpdate", "called");
    }

    public void onPostExecute()
    {
    	Log.d("onPostExecute", "called");
    }

    public void onCancelled()
    {
    	Log.d("onPostCancelled", "called");
    }

    // -------------------------------------------------------------------
    // Define message object and message handler 
    // -------------------------------------------------------------------
    
    private static class CommandResult
    {
        final UICommand command;

        CommandResult(UICommand task)
        {
            this.command = task;
        }
    }    
    
    /**
     * Message handler for signalling out of the command thread.
     * 
     */
    private static class InternalHandler extends Handler
   {
       @Override
        public void handleMessage(Message message)
       {
            CommandResult result = (CommandResult)message.obj;

            switch (message.what)
            {
                case MESSAGE_POST_START:
                    result.command.onPreExecute();
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.command.onProgressUpdate();
                    break;
                case MESSAGE_POST_END:
                    result.command.onPostExecute();
                    result.command.task.done();
                    break;
                case MESSAGE_POST_CANCELLED:
                    result.command.onCancelled();
                    break;
                 default:
                    break;
            }
       }
    }	

What is this all about? Well, you can’t call methods in your main UI thread (in this case the Geocode Activity) directly from the ‘run’ method of your background thread. If you do you will find your application falling flat on it’s arse with a horrible exception. What you can do is to signal from within your thread to the UI thread by means of message ‘Handler’. This is what we are doing here. The start, end and progress points in the action you are running are ‘published’ to the handler which then calls the appropriate method in your command. Since the command is instantiated within your UI thread (did I fail to mention you have to do this) the callback functions which you can override can call methods in your Activity.

In this example I am overriding ‘onPostExecute’ in my ‘GeoCodeCommand’ command class and it is calling a method in my list adapter which signals to update the list view.

public void onPostExecute() 

{
    adapter.notifyDataSetChanged();
}

You can also use this mechanism to open and close a ‘progress’ dialog or perform any sort of UI operation you like.

Finally the ‘ThreadManager’ class implements a thread pool which can efficiently reuse previous thread instances.

private static final ThreadFactory threadFactory = new ThreadFactory()
{
    private final AtomicInteger count = new AtomicInteger(1);
	
    public Thread newThread(Runnable r)
    {
        return new Thread(r, "Managed Thread #" + count.getAndIncrement());
    }
};
	
private ExecutorService executor = Executors.newCachedThreadPool(threadFactory);

So that’s it. Happy holidays.

Once again, you will find the code here.

General: Progress

I was hoping to get the Android weather app ‘simple weather’ into some sort of semblance of working order before the end of the year but it doesn’t look likely now. I ran up against a problem which showed itself when the phone orientation was flipped repeatedly. Basically my worker thread was holding onto the SQLLite cursor somehow so that when the view adapter went to requery it there was an issue getting hold of it (at least I think that what was causing it).

This problem got me started on examining the UserTask.java class which is bundled into some of the examples at apps-for-android. This is an interesting class and is worth some study. Basically it lets you spawn a background thread to perform some task which will take some initial parameters and return a stated type.

I wasn’t happy with my understanding of what was going on inside this so I set out to write an Android version of the CommandProcessor design pattern.

I think I have it working and what I think I’ll do is forget about the weather application just now and try and write a demo app which will show off what I have discovered when dissecting UserTask.java.

Android: Simple Weather Menu Icons

I have renamed my Android weather application to ‘Simple Weather’.

Menu with system Icons

Main

Absolutely the last screen shot I promise (until the next one).

You can reuse the system drawables, their id values start with “ic_”. In this context I wanted to reuse icons for ‘Settings’ and ‘About’.

The tricky bit, which isn’t very clear for the documentation or SDK, is the reference to the system icon.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item android:id="@+id/show_settings"
        android:icon="@drawable/android:ic_menu_manage"
        android:title="@string/show_settings" />

    <item android:id="@+id/about"
        android:icon="@drawable/android:ic_menu_help"
        android:title="@string/about" />

</menu>

You can find a complete display of the system drawables here. This list is extremely handy.

Just got to put an nice icon together for this and then I will stick it up on the Android Market for people to download (free). I’m not expecting this to be a big hit or anything as there are weather applications which are amazing (like the Weatherbug one) but it might fill a niche for a simple straight forward forecast plus it’s got the geocoder view which is kind of unique.