1

I am trying to update a google map marker position in a separate thread. I can update the marker fine in the main thread, but as soon as I try it in a separate thread, the app crashes.

Logcat:

06-10 12:35:37.107: E/AndroidRuntime(25915): FATAL EXCEPTION: Thread-2909
06-10 12:35:37.107: E/AndroidRuntime(25915): java.lang.IllegalStateException: Not on the main thread
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.l.a.ce.b(Unknown Source)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.maps.api.android.lib6.d.ct.a(Unknown Source)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.maps.api.android.lib6.d.aq.a(Unknown Source)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.android.gms.maps.model.internal.t.onTransact(SourceFile:73)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at android.os.Binder.transact(Binder.java:380)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.android.gms.maps.model.internal.zzi$zza$zza.setPosition(Unknown Source)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.android.gms.maps.model.Marker.setPosition(Unknown Source)

and the thread:

new Thread(new Runnable() {
    Marker mkr = marker;
    public void run(){
        double lng = 78.486671;
        double lat = 17.385044;
        mkr.setPosition(new LatLng(lat, lng));
    }
}).start();
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
Brendan Cordingley
  • 190
  • 1
  • 4
  • 20
  • As the error states, you cannot update markers off of the main UI thread. What are you trying to accomplish by doing it on a separate thread? – Dan Harms Jun 10 '15 at 18:59
  • Im tracking something and need to mark its position on a map. The lng and lat of the object will keep changing and I would like to update a marker to point to its location. – Brendan Cordingley Jun 10 '15 at 19:07
  • You could use `runOnUiThread()` in order to modify the Marker position inside your worker thread, for an example see here: http://stackoverflow.com/questions/11140285/how-to-use-runonuithread/11140429#11140429 – Daniel Nugent Jun 10 '15 at 19:17
  • !!!GREAT EXAMPLE!!! works great, thanks for the quick help! – Brendan Cordingley Jun 10 '15 at 19:25

1 Answers1

2

You could use runOnUiThread() in order to modify the Marker position inside your worker thread, for an example see here.

In your case it would be something like this:

    new Thread(new Runnable() {
        Marker mkr = marker;
        public void run(){

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    double lng = 78.486671;
                    double lat = 17.385044;
                    mkr.setPosition(new LatLng(lat, lng));
                }
            });

        }
    }).start();
Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137