Android Location is Null While Enabled - java

I am getting a null location when setting the longitutde and lattitude. I am not sure what I am doing wrong. I debugged this code with Location Services turned on and off. When they were on, the GPS_PROVIDER if statement would be true, and when they were off it neither of the conditions would be true and it would go to the else statement. However even when it confirmed the provider was enabled, the call to getLastKnownLocation returned null. Any ideas as to why?
private void setCoordinates(Context context) {
LocationManager lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Location location = null;
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else {
Log.e("AlarmLocation", "unable to get location");
}

Related

Android APP crash on getLastKnownLocation()

I'm developing an Android app which achieve the position through NETWORK_PROVIDER, but I have problems on executing it on Android 7 (while it correctly works on previous versions). This is the code:
LocationManager posM;
double latitude;
double longitude;
List<Address> addresses = null;
try {
posM = (LocationManager) getSystemService(LOCATION_SERVICE);
Location location = posM.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
Geocoder geocoder;
geocoder = new Geocoder(Activity1.this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
I don't know why it crashes on Android 7... Thank you for help
Because getLastKnownLocation returns null most of the time. The system generally doesn't know your location. Use requestLocationUpdates or requestSingleUpdate to turn on the location detection and get the actual location.

Android LocationListener- requestLocationUpdates

I try to get my current location. First I created LocationListener:
public LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
myLocation = new LatLng(latitude, longitude);
}
};
The in onCreate method I try to cal requestLocatonUpates on LocationManager:
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,500f,mLocationListener);
But I get an error:
Cannot resolve method requestLocationUpdates(java.langString, long, float,com.google.android.gms.location.LocationListener)
requestLocationUpdates is a method provided in FusedLocationAPi. You should use LocationServices.FusedLocationApi.requestLocationUpdates method.
So you have to create a googleApiClient and a location request.
You can found it here : https://developer.android.com/training/location/index.html.

Why is this double null?

I' m in a service, and I just need the latitude and longitude. Just two doubles. So, I did the following:
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
}
For some reason, the latitude and latitude are null. The documentation says this is possible if the information for location is unavailable, but it should be available, since I first check if the permissions are there in the if statement, right? In the phone that I am testing on, I do have location enabled. Why is the latitude and longitude null?
If you try this instead, what is the output?
locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
It's because, even if location is enabled, there is no "lastKnownLocation" available yet. If you go to (for example) google maps app and ask for current location, after location is successfully fetched, go to your app and it will work (lat and lon != null).
EDIT: I don't know the code for android location service API, but for google maps API is something like this (i'm sure is similar):
public void methodThatUseLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, MainActivity.REQUEST_LOCATION);
} else {
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
Double latitude = lastLocation.getLatitude();
Double longitude = lastLocation.getLongitude();
// do something with latitude and longitude
} else {
requestLocationUpdate();
}
}
}
private void requestLocationUpdate() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, MainActivity.REQUEST_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
The reason is, you are checking last known location, and if there were no locations previously fetched by this provider, all corresponding parameters will be null. Method getLastKnownLocation reuses information fetched by other apps/services, and it can happen that there were no information saved.
You can try to make single location update using method requestSingleUpdate, so you won't depend on your device state.

Not able to display path from current location to destination google maps V2

I am trying to draw path from current location to destination using the answer Android: How to draw route directions google maps API V2 from current location to destination.
But in place of the hard coded I longitude and Latitude of the current location I want to use my real location. But whenever I try to do that, the App is crashing with error in line location = mMap.getMyLocation();
Any help is appreciated.
MapsActivity.Java
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Location location;
LatLng myPosition;
GMapV2Direction md;
LatLng fromPosition = getYourLocation();
LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
md = new GMapV2Direction();
setUpMapIfNeeded();
LatLng coordinates = new LatLng(13.685400079263206, 100.537133384495975);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));
mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));
Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
/*myPosition = getLocation();
ZoomCurrentLocation(myPosition);*/
}
}
}
private LatLng getYourLocation() {
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
}
LatLng latLng = new LatLng(latitude, longitude);
return latLng;
}
private void ZoomCurrentLocation(LatLng myPosition)
{
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16));
}
private void setUpMap(LatLng myPosition) {
mMap.addMarker(new MarkerOptions().position(myPosition).title("Marker"));
}
}
Do you mean location = mMap.getMyLocation(); is the method getYourLocation() in the code, and the crash is at Location location = locationManager.getLastKnownLocation(provider); ?
If so, it may cause by NullPointer Exception, you need use new api FusedLocationApi to avoid getLastLocation null pointer.
Please check here to know how to use it. And here is the code for it on my github.
For the destination you can check here to get some idea.

get latitude and longitude in Android without show the map [duplicate]

This question already has an answer here:
android requestLocationUpdates failing
(1 answer)
Closed 2 years ago.
Is there a way to obtain information without displaying the map?
I want get my coordinate of my place during the work with other activity.
tnx a lot.
By Using LocationManager you can get lat and lang :
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
Using this code able to get latitude and Longitude values and make
sure before using application you got permission from manifest for accessing location
if(isGPS) {
Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
double lat=location.getLatitude();
double lng=location.getLongitude();
Toast.makeText(getApplicationContext(),lat+"and"+lng, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
display("GPS not Enabled");
}
Manifest permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Use this if you want to get lat lon without internet
LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLongitude();
longitude = location.getLatitude();

Categories