Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.IllegalStateException: Not on the main thread Google Maps

I am getting the above error when my Android app code receives data from a cloud messaging platform and I try to put that data on the map -

    java.lang.IllegalStateException: Not on the main thread
    at maps.w.c.a(Unknown Source)
    at maps.y.F.a(Unknown Source)
    at maps.ad.u.b(Unknown Source)
    at vo.onTransact(:com.google.android.gms.DynamiteModulesB:92)
    at android.os.Binder.transact(Binder.java:380)
    at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.animateCamera(Unknown Source)
    at com.google.android.gms.maps.GoogleMap.animateCamera(Unknown Source)
    at com.pabba.mtracker.tracking.view.TrackingActivity.onLocationReceived(TrackingActivity.java:54)

The following is the code that is called by my presenter (I am using MVP Pattern for my android app) when it receives a Location message from the Cloud Messaging service.

@Override
public void onLocationReceived(LatLng latLng) {
    Log.i(TAG, latLng.toString());
    mGoogleMap.addPolyline(new PolylineOptions().add(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(latLng)
            .zoom(13).build()));
}

And the error is occurring in the addPolyLine function call. Please tell me what can be done to resolve it.

like image 270
Vinay Nikhil Avatar asked Sep 05 '16 13:09

Vinay Nikhil


1 Answers

you must run this code in the UIThread:

activity.runOnUIThread(new Runnable(){
    public void run(){
        mGoogleMap.addPolyline(new PolylineOptions().add(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(latLng)
        .zoom(13).build()));
    }
});
like image 143
Khalid Taha Avatar answered Sep 28 '22 03:09

Khalid Taha