I want the location of user and that too just once after that user navigates on his own
locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE
The getLastKnownLocation method will only return a location if the gps LocationProvider has stored a location somewhere. If the user has not yet used the gps on his device long enough to obtain a valid GPS fix the method will return null.
Even if you retrieve a location check the time of the location, there is no guarantee that the location isn't very very old.
It's not enough to just get a locationManager and call getLastKnownLocation()
because until there is an update there will be no "last known location"
You are missing that request provided by the LocationManager class:
public void requestLocationUpdates(java.lang.String provider,
long minTime,
float minDistance,
android.location.LocationListener listener)
If your activity implements LocationListener as mine did, you can pass in "this" as the LocationListener for a call originating in a method of that class. Otherwise, there are several other overloads taking Activity or Looper classes instead.
locationManager.requestLocationUpdates(provider, minTime, minDistance, this);
In order to make sure the device is getting a location, request updates - but you also may
want to put guards for failure to find providers or getLastKnownLocation
returning null.
locationManager.requestLocationUpdates(provider, 1, 0, this);
mostRecentLocation = locationManager.getLastKnownLocation(provider);
if(mostRecentLocation == null)
// lower your expectations, or send user message with Toast or something similar
Tell the user to turn on their location sharing or other provider services.