2

i try to get gps data. But gps data return null value. When i looked, following 'location' is return null, so i could not get gps data.
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

My code is following;

 protected LocationManager locationManager; public GPSTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled) { } else if (!isGPSEnabled && !isNetworkEnabled) { } else { this.canGetLocation = true; if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } 

i wait your help. Thanks

3
  • I found out that sometimes the function getLastKnownLocation() can return null if the user hasn't activated/used the location source for a while. It's better to check like you do. If it's null, then you have to wait for the next location update Commented Mar 27, 2013 at 22:39
  • Or set up a requestSingleUpdate or requestLocationUpdates to turn on the GPS yourself. Commented Mar 27, 2013 at 22:52
  • If the provider is currently disabled, null is returned. I use GPS_PROVIDER. How can i enable? Commented Mar 27, 2013 at 23:11

2 Answers 2

1

Have you set these in your manifest?

<uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
Sign up to request clarification or add additional context in comments.

Comments

1

I changed like following code, then worked successfully.

String bestProvider = locationManager.getBestProvider(criteria, false); locationManager.requestLocationUpdates(bestProvider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); if (locationManager != null) { location = locationManager.getLastKnownLocation(bestProvider); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.