Simple GoogleMaps with Threads

Tutorials that use the MapActivity. Many using GPS functionality.

Simple GoogleMaps with Threads

Postby michels » Thu Sep 25, 2008 1:10 pm

Simple GoogleMaps with Threads
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.

Image



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.
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class simpleGoogleMaps extends MapActivity implements runnable{
  2.   public void onCreate(Bundle savedInstanceState) {
  3.   Thread thread = new Thread(this);
  4.   thread.start();
  5.   }
  6.  
  7.   public void run() {
  8.     //do something
  9.   }
  10. }
  11.  
Parsed in 0.032 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:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. btnSearch.setOnClickListener(new OnClickListener() {
  2.   public void onClick(View v) {
  3.     //Show a progress dialog
  4.     pd = ProgressDialog.show(simpleGoogleMaps.this, "Working..", "Searching your address", true, false);
  5.    
  6.     //create a new thread
  7.     searchAdress = new Thread() {
  8.       public void run(){
  9.         //action of the thread
  10.       }
  11.     }
  12.   }
  13. });
  14.  
Parsed in 0.032 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.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. btnSearch.setOnClickListener(new OnClickListener() {
  2.   public void onClick(View v) {
  3.     //Show a progress dialog
  4.     pd = ProgressDialog.show(simpleGoogleMaps.this, "Working..", "Searching your address", true, false);
  5.    
  6.     //create a new thread
  7.     searchAdress = new Thread() {
  8.       public void run(){
  9.         String addressInput = adress.getText().toString(); // Get input text
  10.         try {
  11.           foundAdresses = gc.getFromLocationName(addressInput, 5); // Search addresses
  12.         } catch (Exception e) {
  13.           // @todo: Show error message
  14.         }
  15.         showAdressResults.sendEmptyMessage(0); 
  16.       }
  17.     }
  18.     searchAdress.start();
  19.   }
  20. });
  21.  
Parsed in 0.036 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

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. private Handler showAdressResults = new Handler() {
  2.   public void handleMessage(Message msg) {
  3.   }
  4. }
  5.  
Parsed in 0.035 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
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. private Handler showAdressResults = new Handler() {
  2.   public void handleMessage(Message msg) {
  3.     if (foundAdresses.size() == 0) { // if no address found,
  4.       // display an error
  5.       Dialog locationError = new AlertDialog.Builder(simpleGoogleMaps.this)
  6.       .setIcon(0)
  7.       .setTitle("Error")
  8.       .setPositiveButton(R.string.ok, null)
  9.       .setMessage("Sorry, your address doesn't exist.")
  10.     .create();
  11.     locationError.show();
  12.        
  13.     } else { // else display address on map
  14.       for (int i = 0; i < foundAdresses.size(); ++i) {
  15.       // Save results as Longitude and Latitude
  16.       Address x = foundAdresses.get(i);
  17.       lat = x.getLatitude();
  18.       lon = x.getLongitude();
  19.     }
  20.     navigateToLocation((lat * 1000000), (lon * 1000000),myMap); // display the found address
  21.   }
  22. }
  23.  
Parsed in 0.039 seconds, using GeSHi 1.0.8.4


Full Source Code
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. //lots of imports.. see attached source
  2. public class simpleGoogleMaps extends MapActivity {
  3.         protected boolean isRouteDisplayed() {
  4.                 return false;
  5.         }
  6.  
  7.         //lots of variables here
  8.  
  9.         @Override
  10.         public void onCreate(Bundle savedInstanceState) {
  11.                 super.onCreate(savedInstanceState);
  12.                 setContentView(R.layout.main);
  13.  
  14.                 myMap = (MapView) findViewById(R.id.simpleGM_map); // Get map from XML
  15.                 btnSearch = (Button) findViewById(R.id.simpleGM_btn_search); // Get button from xml
  16.                 adress = (EditText) findViewById(R.id.simpleGM_adress); // Get address from XML
  17.  
  18.                 gc = new Geocoder(this); // create new geocoder instance
  19.  
  20.                 btnSearch.setOnClickListener(new OnClickListener() {
  21.                         public void onClick(View v) {
  22.                                
  23.                                 pd = ProgressDialog.show(simpleGoogleMaps.this, "Working..", "Searching your address", true, false); //Show a progress dialog
  24.                        
  25.                                
  26.                                 searchAdress = new Thread() {
  27.                                         public void run(){
  28.                                                 String addressInput = adress.getText().toString(); // Get input text
  29.                                                 try {
  30.                                                         foundAdresses = gc.getFromLocationName(addressInput, 5); // Search addresses
  31.                                                         Thread.sleep(1500); //just to show you that it works <img src="http://www.anddev.org/images/smilies/smile.png" alt=":-)" title="Smile" />
  32.                                                 } catch (Exception e) {
  33.                                                         // @todo: Show error message
  34.                                                 }
  35.                                                 showAdressResults.sendEmptyMessage(0);                                         
  36.                                         }
  37.                                 };
  38.                                 searchAdress.start();
  39.                         }
  40.                 });
  41.         }
  42.        
  43.         private Handler showAdressResults = new Handler() {
  44.                 @Override
  45.                 public void handleMessage(Message msg) {
  46.                         pd.dismiss();
  47.                    
  48.                                 if (foundAdresses.size() == 0) { // if no address found,
  49.                                         // display an error
  50.                                         Dialog locationError = new AlertDialog.Builder(
  51.                                                         simpleGoogleMaps.this).setIcon(0).setTitle(
  52.                                                         "Error").setPositiveButton(R.string.ok, null)
  53.                                                         .setMessage("Sorry, your address doesn't exist.")
  54.                                                         .create();
  55.                                         locationError.show();
  56.                                        
  57.                                 } else { // else display address on map
  58.                                         for (int i = 0; i < foundAdresses.size(); ++i) {
  59.                                                 // Save results as Longitude and Latitude
  60.                                                 // @todo: if more than one result, then show a
  61.                                                 // select-list
  62.                                                 Address x = foundAdresses.get(i);
  63.                                                 lat = x.getLatitude();
  64.                                                 lon = x.getLongitude();
  65.                                         }
  66.                                         navigateToLocation((lat * 1000000), (lon * 1000000),myMap); // display the found address
  67.                                 }
  68.                                  
  69.                 }
  70.             }; 
  71.  
  72.         /**
  73.          * Navigates a given MapView to the specified Longitude and Latitude
  74.          *
  75.          * @param latitude
  76.          * @param longitude
  77.          * @param mv
  78.          */
  79.         public static void navigateToLocation(double latitude, double longitude, MapView mv) {
  80.                 GeoPoint p = new GeoPoint((int) latitude, (int) longitude); // new
  81.                 // GeoPoint
  82.                 mv.displayZoomControls(true); // display Zoom (seems that it doesn't
  83.                 // work yet)
  84.                 MapController mc = mv.getController();
  85.                 mc.animateTo(p); // move map to the given point
  86.                 int zoomlevel = mv.getMaxZoomLevel(); // detect maximum zoom level
  87.                 mc.setZoom(zoomlevel - 1); // zoom
  88.                 mv.setSatellite(false); // display only "normal" mapview
  89.         }
  90. }
  91.  
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
Attachments
simpleGoogleMaps-withThread.tar
Full source code
(74.5 KiB) Downloaded 2591 times
Last edited by michels on Thu Oct 16, 2008 9:26 pm, edited 1 time in total.
michels
Junior Developer
Junior Developer
 
Posts: 17
Joined: Wed Sep 24, 2008 12:37 pm
Location: Germany

Top

Postby plusminus » Thu Sep 25, 2008 2:23 pm

:) fine once again :!:
One thing I'd mention is that you should pass a Constant to [font=Courier New]showAdressResults.sendEmptyMessage(0);[/font] instead of just '0'.

So you could [font=Courier New]switch(incomingMessage.what)[/font] in [font=Courier New]myHandler.handleMessage(Message incomingMessage)[/font] to handle the messages based on their [font=Courier New]what[/font]-id.

Best Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby ninor » Thu Sep 25, 2008 9:41 pm

Very useful and clear example! :)
User avatar
ninor
Moderator
Moderator
 
Posts: 180
Joined: Thu Aug 14, 2008 6:30 pm
Location: Barcelona, Spain

Postby happy_bob » Tue Oct 28, 2008 1:29 pm

so why doesn't the map appear for me? it always seems to be empty.
Image
Attachments
android.JPG
mapview
android.JPG (40.78 KiB) Viewed 25231 times
happy_bob
Freshman
Freshman
 
Posts: 3
Joined: Mon Oct 20, 2008 2:51 pm

Postby michels » Tue Oct 28, 2008 1:52 pm

happy_bob wrote:so why doesn't the map appear for me? it always seems to be empty.


Do you have internet access?
michels
Junior Developer
Junior Developer
 
Posts: 17
Joined: Wed Sep 24, 2008 12:37 pm
Location: Germany

Postby happy_bob » Tue Oct 28, 2008 2:00 pm

michels wrote:
happy_bob wrote:so why doesn't the map appear for me? it always seems to be empty.


Do you have internet access?


yes i have! and it seems to be working in that way that it gives a error message if i search for a city that doesn't exist, for example "blablabla", but it doesnt print the map after it has searched.
I'm quite new at this, does this have something to do with the maps API key?
happy_bob
Freshman
Freshman
 
Posts: 3
Joined: Mon Oct 20, 2008 2:51 pm

Top

Postby plusminus » Tue Oct 28, 2008 2:29 pm

happy_bob wrote:..., does this have something to do with the maps API key?


Seems so, yes.
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby michels » Thu Oct 30, 2008 5:03 pm

happy_bob wrote:does this have something to do with the maps API key?


Yes, today I've tested it with a valid API Key and it works well.
michels
Junior Developer
Junior Developer
 
Posts: 17
Joined: Wed Sep 24, 2008 12:37 pm
Location: Germany

Postby ndroid » Thu Dec 18, 2008 6:10 am

Hi
my observation is that i get result for first search only.
other searches result in an exception.
do i need to get geocoder for every search.
thanks
ndroid
Junior Developer
Junior Developer
 
Posts: 15
Joined: Mon Dec 15, 2008 1:29 pm

Postby sitara » Fri Jan 02, 2009 6:00 am

Hi ,
i am getting the same blank map as happy_bob.

i have gotten my api key, but where do i put the key? which file should i put it in?


Sitara
sitara
Junior Developer
Junior Developer
 
Posts: 13
Joined: Thu Nov 27, 2008 8:27 am

Postby winvinay » Tue Jan 20, 2009 10:07 am

sitara wrote:Hi ,
i am getting the same blank map as happy_bob.

i have gotten my api key, but where do i put the key? which file should i put it in?


Sitara



Api key should be added in the xml as shown below

<com.google.android.maps.MapView android:id="@+id/simpleGM_map"
android:layout_width="fill_parent" android:layout_height="310px"
android:apiKey="Key" android:layout_x="2px" android:layout_y="100px"
android:clickable="true" />
Vinay H V
Software Engineer
winvinay
Freshman
Freshman
 
Posts: 3
Joined: Tue Jan 20, 2009 10:01 am

not function

Postby android2 » Sun Oct 04, 2009 9:02 pm

I can not see the map I put the API key and there permission.internet what is wrong???
winvinay wrote:
sitara wrote:Hi ,
i am getting the same blank map as happy_bob.

i have gotten my api key, but where do i put the key? which file should i put it in?


Sitara



Api key should be added in the xml as shown below

<com.google.android.maps.MapView android:id="@+id/simpleGM_map"
android:layout_width="fill_parent" android:layout_height="310px"
android:apiKey="Key" android:layout_x="2px" android:layout_y="100px"
android:clickable="true" />
android2
Developer
Developer
 
Posts: 48
Joined: Sun Oct 04, 2009 8:34 pm

Re: not function

Postby android2 » Mon Oct 05, 2009 3:40 pm

How do you get fingerprint for 'api key for Android???
android2 wrote:I can not see the map I put the API key and there permission.internet what is wrong???
winvinay wrote:
sitara wrote:Hi ,
i am getting the same blank map as happy_bob.

i have gotten my api key, but where do i put the key? which file should i put it in?


Sitara



Api key should be added in the xml as shown below

<com.google.android.maps.MapView android:id="@+id/simpleGM_map"
android:layout_width="fill_parent" android:layout_height="310px"
android:apiKey="Key" android:layout_x="2px" android:layout_y="100px"
android:clickable="true" />
android2
Developer
Developer
 
Posts: 48
Joined: Sun Oct 04, 2009 8:34 pm

Re: Simple GoogleMaps with Threads

Postby Dhr » Thu Sep 16, 2010 11:07 am

Hello..

Thanks for this tutorial.
It shows an erroe like this:- The application show Address has stopped unexpectedly. Please try again.

What is the problem??

Can anyone suggest me??

~DHR.
User avatar
Dhr
Junior Developer
Junior Developer
 
Posts: 24
Joined: Thu Aug 19, 2010 11:59 am
Location: Ahd, Gujarat, India

Re: Simple GoogleMaps with Threads

Postby leehong1076 » Thu Dec 09, 2010 11:37 am

it's very useful. Thanks alot
leehong1076
Freshman
Freshman
 
Posts: 2
Joined: Tue Dec 07, 2010 4:02 am

Top
Next

Return to Map Tutorials

Who is online

Users browsing this forum: No registered users and 4 guests