My Current Location Always Returns Null. How to Fix This

My current location always returns null. How can I fix this?

getLastKnownLocation() uses the location(s) previously found by other applications. if no application has done this, then getLastKnownLocation() will return null.

One thing you can do to your code to have a better chance at getting as last known location- iterate over all of the enabled providers, not just the best provider. For example,

private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
ALog.d("last known location, provider: %s, location: %s", provider,
l);

if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
ALog.d("found best last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}

If your app can't deal without having a location, and if there's no last known location, you will need to listen for location updates. You can take a look at this class for an example,

https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java

See the method onStartCommand(), where it checks if the network provider is enabled. If not, it uses last known location. If it is enabled, it registers to receive location updates.

current location is always null

pleas check your manifest file.whether have you added those permissions or not.

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>

See the updated answer:

protected void showCurrentLocation() 
{
geocoder = new Geocoder(this);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
myLocationListener
);
timer = new Timer();
timer.schedule(new GetLastLocation(),20000);

}

class GetLastLocation extends TimerTask {

@Override
public void run() {
timer.cancel();
locationManager.removeUpdates(locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
System.out.println("loc.."+location);
if (location != null)
{
String message = String.format("Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Toast.makeText(ShowActivity.this, message,
Toast.LENGTH_LONG).show();
//acTextView.setText(message);
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); //<10>
for (Address address : addresses) {
System.out.println("my location .."+address.getAddressLine(0));
acTextView.setText(address.getAddressLine(0));
}

} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}
else
{
AlertDialog.Builder alertbox1 = new AlertDialog.Builder(this);
alertbox1.setMessage("No GPS or network ..Signal please fill the location manually!");
alertbox1.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1)
{}});
alertbox1.show();
}
}
return;
}
}

/** The location listener. */
LocationListener myLocationListener = new LocationListener() {

public void onLocationChanged(Location location) {

}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};

android : CurrentLocation always return null value

There are several reasons you are getting null. Most likely, it doesn't have a previous location to pull from. Remember that getLastLocation doesn't actually go out and get a fresh location; it just grabs the last one that your phone has. Your phone will pick up location data from a variety of sources/methods, and this is the data being used. From my experience it is often up to a few minutes old.

I would:

1) Check that you're not using a sim
2) Check that your GPS is working on your phone (is Google Maps working?)
3) Try forcing a loction update (LocationManager.requestLocationUpdate(...) as seen here) and debug from there.

I believe check permission is a warning as long as you also support SDK <21.

Fused Location always returns null

Add this code to your onConnected, thats where it would get Last Known Location.

private static Location mLastLocation;
private static GoogleApiClient mGoogleApiClient;
private static Context context;

// added
private LocationRequest mLocationRequest;
private Double latitude;
private Double longitude;
private String TAG = ""; // set your TAG

@Override
public void onConnected(Bundle bundle) {

if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation == null){
startLocationUpdates();
}

if (mLastLocation != null) {
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();

// set your tag
Log.d(TAG, String.valueOf(latitude));
Log.d(TAG, String.valueOf(longitude));

} else {
Toast.makeText(context, "Location not Detected, Did you turn off your location?", Toast.LENGTH_SHORT).show();
}
}

protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(30 * 1000)
.setFastestInterval(5 * 1000);

// Request location updates
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

And remove synchronized from your method, Just make it public. Something like this below:

public void buildGoogleApiClient() { }


Related Topics



Leave a reply



Submit