Syamsul Maarif Syamsul Maarif - 6 months ago 43
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) {

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

callListVolley(latitude, longitude);
Toast.makeText(getBaseContext(), "Lokasi device pengguna tidak ditemukan.\nMohon hidupkan GPS.",
callListVolley(-6.894796, 110.638413);

so when i run and then this error appear

Process: com.example.invader.haversine, PID: 5913
java.lang.IllegalArgumentException: invalid provider: null
at android.location.LocationManager.checkProvider(
at android.location.LocationManager.getLastKnownLocation(
**at com.example.invader.haversine.MainActivity.lokasi(
at com.example.invader.haversine.MainActivity.access$000(
at com.example.invader.haversine.MainActivity$**

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download