Simple GoogleMaps with Threads
Using Threads and Handlers the Android-Way
Using Threads and Handlers the Android-Way
This tutorial is also available in german at my android weblog Androidianer.de
This tutorial based on the Simple GoogleMaps tutorial I wrote yesterday, where we learned how to convert an address in longitude and latitude by using the GeoCoder class. As read in the APIs, "it may be useful to call this method from a thread separate from your primary UI thread." So we will do this today.
How it looks like:
Like the Simple GoogleMaps. But with a progress dialog that is shown everytime a new address is searched.

What is a thread?
You can read this chapter in the java docs for better understanding and to see how threads are used.
Read also this in the android API.
Or just accept the following sentence:
A thread is a parallel process - While we search an adress, we can also display a progress dialog.
How can we use threads in Android?
We can implement the Runnable interface and create a run() function.
Using java Syntax Highlighting
- public class simpleGoogleMaps extends MapActivity implements runnable{
- public void onCreate(Bundle savedInstanceState) {
- Thread thread = new Thread(this);
- thread.start();
- }
- public void run() {
- //do something
- }
- }
Parsed in 0.030 seconds, using GeSHi 1.0.8.4
You can read this tutorial from helloandroid.com to see how this works.
But there is also an alternative way I like much more
GeoCoder with threads
1.If you look at the Simple GoogleMaps code, you will see, that everything important, like the address search, happens in the OnClickListener function.
But now, everything we do in the OnClickListener is to display a progress dialog and start parallel a new thread:
Using java Syntax Highlighting
- btnSearch.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- //Show a progress dialog
- pd = ProgressDialog.show(simpleGoogleMaps.this, "Working..", "Searching your address", true, false);
- //create a new thread
- searchAdress = new Thread() {
- public void run(){
- //action of the thread
- }
- }
- }
- });
Parsed in 0.031 seconds, using GeSHi 1.0.8.4
2.While the progress dialog is shown, we will search for the address. So we add the search function in our thread and start it.
Using java Syntax Highlighting
- btnSearch.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- //Show a progress dialog
- pd = ProgressDialog.show(simpleGoogleMaps.this, "Working..", "Searching your address", true, false);
- //create a new thread
- searchAdress = new Thread() {
- public void run(){
- String addressInput = adress.getText().toString(); // Get input text
- try {
- foundAdresses = gc.getFromLocationName(addressInput, 5); // Search addresses
- } catch (Exception e) {
- // @todo: Show error message
- }
- showAdressResults.sendEmptyMessage(0);
- }
- }
- searchAdress.start();
- }
- });
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
3.Now our application shows a nifty progress dialog and searches in the background an entered address. Nice!
After the search is ready (end of the try-catch-statement) we send a message to showAdressResults. We haven't defined that yet, so let's do
Using java Syntax Highlighting
- private Handler showAdressResults = new Handler() {
- public void handleMessage(Message msg) {
- }
- }
Parsed in 0.034 seconds, using GeSHi 1.0.8.4
4.showAdressResults is defined as a handler, that waits all the time for a message.
When he gets one, he knows that we found an address. Then we dismiss the progress dialog and display the map.
Here we go
Using java Syntax Highlighting
- private Handler showAdressResults = new Handler() {
- public void handleMessage(Message msg) {
- if (foundAdresses.size() == 0) { // if no address found,
- // display an error
- Dialog locationError = new AlertDialog.Builder(simpleGoogleMaps.this)
- .setIcon(0)
- .setTitle("Error")
- .setPositiveButton(R.string.ok, null)
- .setMessage("Sorry, your address doesn't exist.")
- .create();
- locationError.show();
- } else { // else display address on map
- for (int i = 0; i < foundAdresses.size(); ++i) {
- // Save results as Longitude and Latitude
- Address x = foundAdresses.get(i);
- lat = x.getLatitude();
- lon = x.getLongitude();
- }
- navigateToLocation((lat * 1000000), (lon * 1000000),myMap); // display the found address
- }
- }
Parsed in 0.039 seconds, using GeSHi 1.0.8.4
Full Source Code
Using java Syntax Highlighting
- //lots of imports.. see attached source
- public class simpleGoogleMaps extends MapActivity {
- protected boolean isRouteDisplayed() {
- return false;
- }
- //lots of variables here
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- myMap = (MapView) findViewById(R.id.simpleGM_map); // Get map from XML
- btnSearch = (Button) findViewById(R.id.simpleGM_btn_search); // Get button from xml
- adress = (EditText) findViewById(R.id.simpleGM_adress); // Get address from XML
- gc = new Geocoder(this); // create new geocoder instance
- btnSearch.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- pd = ProgressDialog.show(simpleGoogleMaps.this, "Working..", "Searching your address", true, false); //Show a progress dialog
- searchAdress = new Thread() {
- public void run(){
- String addressInput = adress.getText().toString(); // Get input text
- try {
- foundAdresses = gc.getFromLocationName(addressInput, 5); // Search addresses
- Thread.sleep(1500); //just to show you that it works <img src="http://www.anddev.org/images/smilies/smile.png" alt=":-)" title="Smile" />
- } catch (Exception e) {
- // @todo: Show error message
- }
- showAdressResults.sendEmptyMessage(0);
- }
- };
- searchAdress.start();
- }
- });
- }
- private Handler showAdressResults = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- pd.dismiss();
- if (foundAdresses.size() == 0) { // if no address found,
- // display an error
- Dialog locationError = new AlertDialog.Builder(
- simpleGoogleMaps.this).setIcon(0).setTitle(
- "Error").setPositiveButton(R.string.ok, null)
- .setMessage("Sorry, your address doesn't exist.")
- .create();
- locationError.show();
- } else { // else display address on map
- for (int i = 0; i < foundAdresses.size(); ++i) {
- // Save results as Longitude and Latitude
- // @todo: if more than one result, then show a
- // select-list
- Address x = foundAdresses.get(i);
- lat = x.getLatitude();
- lon = x.getLongitude();
- }
- navigateToLocation((lat * 1000000), (lon * 1000000),myMap); // display the found address
- }
- }
- };
- /**
- * Navigates a given MapView to the specified Longitude and Latitude
- *
- * @param latitude
- * @param longitude
- * @param mv
- */
- public static void navigateToLocation(double latitude, double longitude, MapView mv) {
- GeoPoint p = new GeoPoint((int) latitude, (int) longitude); // new
- // GeoPoint
- mv.displayZoomControls(true); // display Zoom (seems that it doesn't
- // work yet)
- MapController mc = mv.getController();
- mc.animateTo(p); // move map to the given point
- int zoomlevel = mv.getMaxZoomLevel(); // detect maximum zoom level
- mc.setZoom(zoomlevel - 1); // zoom
- mv.setSatellite(false); // display only "normal" mapview
- }
- }
Parsed in 0.048 seconds, using GeSHi 1.0.8.4
Full source code is attached. Hope that helps to understand what a thread is and how it should be used.
Greetings from Germany
Mic

fine once again 





