KISHORE_ZE
KISHORE_ZE

Reputation: 1476

`locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);` always returns true

I am testing an app which uses Location services. And it returns null causing NPE (Null Pointer Exception) whenever my Location Services are turned off. So after some searching I found that

    isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);

should return the correct boolean value but when testing my app it seems to always return true causing a NPE (Null Pointer Exception) and crashing my app.

I also read this question. Which has the exact opposite problem apparently and tried that solution. That also didn't work. I am testing on a Samsung G5. Why is this happening. Is something wrong in the code or is there another solution to my problem.

Here is the code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    isGPSEnabled = false;
    intentThatCalled = getIntent();
    String m2txt = intentThatCalled.getStringExtra("v2txt");
    getLocation(m2txt);
}
public void getLocation(String n2txt) {
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    criteria = new Criteria();
    bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
    location = locationManager.getLastKnownLocation(bestProvider);
    isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
    if (isGPSEnabled==true) {
        Log.e("TAG", "GPS is on");
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Toast.makeText(PlacesDecoder.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
        searchNearestPlace(n2txt);
    }
}

I am still a beginner in android. Please do help.

EDIT: This question seems to have the same problem on the same Hardware model. Is this a Hardware Bug? If it is, is there any other possibility. I will also test on another device Note-4 and let you know.

Upvotes: 0

Views: 1337

Answers (1)

tyczj
tyczj

Reputation: 74046

The solution to your problem is to NEVER assume you have a location, Just because your GPS is enabled does not mean you will get a location.

At any time you can get a null location so instead of worrying about if the GPS is enabled or not you should worry about if your location returned is null or not.

getLastKnownLocation() can return a null if there is no last location

Upvotes: 1

Related Questions