1

I am developing an android application in which I need to get my current Location. I have successfully wrote the code and I am getting my current location using Google Play Service.

The problem is sometimes it gives me the location after a long time. I have noticed that it was only for first use of the app.

Any way to avoid this problem and get the current location fast? Is it related to the version of google play service in my code? (I am not using the last one in fact I am using version 9.8.0.)

abielita
  • 13,147
  • 2
  • 17
  • 59
Kaouther Mefteh
  • 132
  • 2
  • 13

1 Answers1

0

As @tahsinRupam said, avoid using getLastLocation as it has a high tendency to return null. It also does not request a new location, so even if you get a location, it could be very old, and not reflect the current location. You might want to check the sample code in this thread: get the current location fast and once in android.

public void foo(Context context) {
  // when you need location
  // if inside activity context = this;

  SingleShotLocationProvider.requestSingleUpdate(context, 
   new SingleShotLocationProvider.LocationCallback() {
     @Override public void onNewLocationAvailable(GPSCoordinates location) {
       Log.d("Location", "my location is " + location.toString());
     }
   });
}

You might want to verify the lat/long are actual values and not 0 or something. If I remember correctly this shouldn't throw an NPE but you might want to verify that.

Here's another SO post which might help:

Community
  • 1
  • 1
abielita
  • 13,147
  • 2
  • 17
  • 59