Android app stopped unfortunately (Location) - android

I was struggling very long to fix a users location
in a Google maps activity. When i runned it once it worked perfectly,
the marker was spotted at the users location.
But now i ran it again and the app stops with two errors in the stack-trace.
Here are the errors:
at com.doppler.stackingcoder.pechhulp.PechhulpActivity.onLocationChanged(PechhulpActivity.java:87)
at com.doppler.stackingcoder.pechhulp.PechhulpActivity.onMapReady(PechhulpActivity.java:101)
And here are the two methods which have the errors:
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude(); // Line 87
longtitude = location.getLongitude();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.zoomTo(10));
mMap.getUiSettings().setRotateGesturesEnabled(false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(location); // Line 101
LatLng myPosition = new LatLng(latitude, longtitude);
mMap.addMarker(new MarkerOptions().position(myPosition)
.title("Uw Locatie:")
.snippet("Dit is uw locatie")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))
);
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
}

Related

mLastLocation: null, always is null, how can solve it?

mLastLocation: null, always is null, how can solve it?
this is my code
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(TrackingOrder.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(TrackingOrder.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
Log.d("Check-1","ok");
requestRuntimePermission();
}
else
{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//mLastLocation = LocationServices.getFusedLocationProviderClient(this).getLastLocation().addOnSuccessListener(mGoogleApiClient);
Log.d("Check-2","ok");
Log.d("mLastLocation",String.valueOf(mLastLocation));
if(mLastLocation != null)
{
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Log.d("Check - latitude",String.valueOf(latitude));
Log.d("Check - longitude",String.valueOf(longitude));
// Add Marker in your location and move the camera
LatLng yourLocation = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(yourLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
//After add marker for your location, add marker for this order and draw route
drawRoute(yourLocation,Common.currentRequest.getAddress());
}
else
{
Log.d("Error","Cannot get location");
Toast.makeText(this,"Could'nt get your location", Toast.LENGTH_SHORT).show();
}
}
}
this is my mGoogleApiClient code
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
But when I locad this displayLocation funcation, there is problem
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Because the mLastLocation still get null.
So where I need to modify?
there has full code
https://luvtas.com/gmap.txt
There are some edge cases when getLastLocation returns null. Look at this question for more information:
LocationClient getLastLocation() return null
Are you testing on emulator or physical device? Do you have GPS turned on? Do you have permissions defined in Manifest.xml?
Also, in your code, you are listening for location updates in onLocationChanged(Location location). You are storing new received location in mLastLocation and then calling displayLocation(). And then you do mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); in displayLocation() and override value received from onLocationChanged. Maybe not intended?

Can't get location using onLocationChanged

I have been trying to get location from my android application for a long time. I am still unable to fetch the location. the onLocationChanged is not getting called.
MapsActivity2.java
public class MapsActivity2 extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
//Location location1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(this,"Permission Missing",Toast.LENGTH_LONG).show();
return;
}
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng=new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Bus Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,17.0f));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s)
{
Toast.makeText(MapsActivity2.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng=new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Bus Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,17.0f));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s)
{
Toast.makeText(MapsActivity2.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
});
}
/*location1=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location1!=null)
{
double latitude = location1.getLatitude();
double longitude = location1.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("Bus Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
}*/
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Don't use new LocationListener() in this line locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() .
Create a listener object and use that, or simply use this.
new LocationListener()
is different which you're accessing .
Lots of things could change the result. The first one seems permission, so if the app isn't granted to use them then it'll be returned and wont make any location request.
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) {
...
return;
}
Others could be statuses of providers. So if they are not enabled, wont make any location request too
One for network provider
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
And gps provider
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
This code is also error-prone.
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) {
...
return;
}
You saying there, don't work if gps and network permissions aren't granted. But work if any of them granted.
Then you are making location requests without knowing which one is granted.
Finally, causing the not granted one will throw SecurityException

Zoom Google Maps Android Firebase

I'm doing my car tracking application. The problem is that when I zoomed in or out, the zoom restarts its position. And when I look at another part of the map, it returns me to my location. How can I solve that?
public void onLocationChanged(Location location) {
if(getApplicationContext()!=null){
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
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(CustomerMapActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
The issue is, with every new location update, your are moving and zooming the camera so you need remove
public void onLocationChanged(Location location) {
if(getApplicationContext()!=null){
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
// remove to stop frequent camera movement
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
or alternatively, you can increase the location retrieval interval to give user some more time as
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);

android - onLocationChanged never called

I am currently implementing a feature of getting user's current location with Google API.
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // user location center in map (every update)
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
#Override
public void onConnected(#Nullable Bundle bundle) {
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) {
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(DISPLACEMENT)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}else{
}
}
However, onLocationChanged callback function is never triggered when I requestLocationUpdates in onConnected. I have log several status out, showing that mLocationRequest is created and requestLocationUpdates is called.
Any ideas on this? Thank you all!

How to get current location using googleapiClient then put marker

I do want to get current location with GoogleApiClient with this code below,
#Override
public void onConnected(#Nullable Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null)
{
currentLat = mLastLocation.getLatitude();
currentLon = mLastLocation.getLongitude();
}else
{
Toast.makeText(getApplicationContext(), "Cannot get lat and lon", Toast.LENGTH_SHORT).show();
}
}
then after that i do want to put marker on current location, my problem is mLastlocation still null
#Override
public void onMapReady(GoogleMap googleMap) {
dGoogleMap = googleMap;
if(mLastLocation != null)
{
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(currentLat, currentLon))
.title("My Current Location");
dGoogleMap.addMarker(marker);
dGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(currentLat, currentLon), 16));
}
}
Or this is my fault missunderstand the flow of async, or just my poor logic needs to be improved.
Put below line in your onMapReady method
dGoogleMap.setMyLocationEnabled(true);

Categories

Resources