Reputation: 3349
I'm writing my app to check if the location is turned on in the app. I have the below check. When the location isn't turned on, inside the getLocation()
method, I have an AlertDialog that gets built to alert the user that they must turn on their location, but instead of displaying the alert, the app crashes with a nullpointer
exception because I try to access the size of the arrayList getLocation()
returns.
This is my call to the line that crashes it.
latLongValues = getLocation();
Log.d("LATLONG VALUES", latLongValues.size() + "");
Here is my getLocation
function
private ArrayList<Double> getLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if(isLocationEnabled(locationManager)){
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
ArrayList<Double> values = new ArrayList<>();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
values.add(latitude);
values.add(longitude);
return values;
}
else if(!isLocationEnabled(locationManager)){
Log.d("LOCATION IS NOT ENABLED", "locatoin not enabled");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Turn on location and click \"OK")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getLocation();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return null;
}
private boolean isLocationEnabled(LocationManager lm){
boolean gps = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gps && !network){
return false;
} else {
return true;
}
}
Upvotes: 0
Views: 45
Reputation: 4358
Because only if the location is enabled, you declared:
ArrayList<Double> values = new ArrayList<>();
What about the second case?
That's why your ArrayList is null when the location is disabled.
Initialize it before the if
And don't return null in the end of the function.
you should return values;
Upvotes: 1