Android - Google Maps - LocationListener - adding the onLocationChanged marker causes the app to crash

I want the marker to show my current location. All required permissions are added. When I comment out mMap.addMarker and mMap.moveCamera the app is running and Googlemaps is displayed. If I allow one of these two in my code, the app crashes before the card even opens.

I tried to remove the marker if it is not null, but that doesn't solve the problem.

Do you guys know how I can get the application to work?

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {


private GoogleMap mMap;
private List<LatLng> fountain = null;
private LocationManager locationManager;
private double posLat;
private double posLng;

private LatLng position;
private Marker mPosition;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    startGPS();


}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(48.16786112327462, 16.383984438313828);
    mPosition = mMap.addMarker(new MarkerOptions().position(sydney).title("Your Position").icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));


}


//--------------------------------------------GPS Listener---------------------------------------
public void startGPS() {

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 5);
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this);
    onLocationChanged(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));

}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 5: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                getDialog2("Keine Erlaubnis für GPS").show();
            }
        }
    }
}


@Override
public void onLocationChanged(Location location) {
    posLat = location.getLatitude();
    posLng = location.getLongitude();

    position = new LatLng(posLat, posLng);

    if (mPosition != null) {
        mPosition.remove();
    }

    mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
            icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

      

// ---------------------------- Helper methods --------------- --- -----------------------------

public Dialog getDialog2(String string) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(string);
    builder.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                @Override

                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    return builder.create();
}


public Dialog getDialog(String string) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(string);
    builder.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    return builder.create();
}

      

}

+3


source to share


1 answer


Ok, I have already solved the problem. So I am posting the solution here.

I have implemented the LocationListener interface in MapsActivity and for some reason it doesn't work that way. I can get the geo coordinates, but as soon as I want to move the camera or add a marker, the app crashes when it opens.

I don't know why, but instead of:

locationManager.requestLocationUpdates (LocationManager.GPS_PROVIDER, 3000, 5, this)



I override the implementation of LocationListener and just create a new one at the position, this ::

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        posLat = location.getLatitude();
                        posLng = location.getLongitude();

                        position = new LatLng(posLat, posLng);

                        if (mPosition != null) {
                            mPosition.remove();
                        }

                        mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
                                icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));

                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));

                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {

                    }

                    @Override
                    public void onProviderEnabled(String provider) {

                    }

                    @Override
                    public void onProviderDisabled(String provider) {

                    }
                }


        );

      

and in this way it works without problem.

+3


source







All Articles