Syamsul Maarif Syamsul Maarif - 1 month ago 18
Android Question

Error locationManager.getLastKnownLocation

i follow tutorial about haversine formula

here is my function lokasi() in MainAcitvity

private void lokasi(){
location = locationManager.getLastKnownLocation(provider);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}

// permintaan update lokasi device dalam waktu 10 detik
locationManager.requestLocationUpdates(provider, 10000, 1, this);

if(location!=null){
onLocationChanged(location);
callListVolley(latitude, longitude);
}else{
Toast.makeText(getBaseContext(), "Lokasi device pengguna tidak ditemukan.\nMohon hidupkan GPS.",
Toast.LENGTH_LONG).show();
callListVolley(-6.894796, 110.638413);
}
}


so when i run and then this error appear

FATAL EXCEPTION: main
Process: com.example.invader.haversine, PID: 5913
java.lang.IllegalArgumentException: invalid provider: null
at android.location.LocationManager.checkProvider(LocationManager.java:1704)
at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1194)
**at com.example.invader.haversine.MainActivity.lokasi(MainActivity.java:84)
at com.example.invader.haversine.MainActivity.access$000(MainActivity.java:36)
at com.example.invader.haversine.MainActivity$1.run(MainActivity.java:73)**


so when i check in logcat the error was in beginning of function but i dont know what should i do

Answer Source

Firstly you should check permission before request location. Secondly you should check if provider exist and if it's enabled like this.

if(locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER) && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
   provider = LocationManager.GPS_PROVIDER;
}

for example if you want to use GPS_PROVIDER