9

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.

dex
  • 5,182
  • 1
  • 23
  • 41
Vinay Nikhil
  • 91
  • 1
  • 1
  • 8

2 Answers2

16

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()));
    }
});
Khalid Taha
  • 3,183
  • 5
  • 27
  • 43
0

The following code will help you. Add your activity.

runOnUiThread(new Runnable() {
   @Override
   public void run() {
      MapView mMapView = (MapView) dialog.findViewById(R.id.mapView);
      MapsInitializer.initialize(context);
      mMapView.onCreate(dialog.onSaveInstanceState());
      mMapView.onResume();
      mMapView.getMapAsync(new OnMapReadyCallback() {
      @Override
      public void onMapReady(final GoogleMap googleMap) {
            LatLng myLocation=new LatLng(Double.parseDouble(lat), Double.parseDouble(lon));
            googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            googleMap.addMarker(new MarkerOptions().position(myLocation).title("My location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
            float zoomLevel = (float) 16.0; //This goes up to 21
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, zoomLevel));  
            googleMap.getUiSettings().setZoomControlsEnabled(true);
         }
      });
   }
});
Sagittarius
  • 355
  • 3
  • 6
  • Welcome to Stack Overflow. Please provide some explanation about provided code and your solution of the problem. – pgk Jan 30 '20 at 14:22