I was wondering if there is a better way to code this piece of code:
private void getLatitudeAndLongitudeFromZipcode() {
String zipcode = mSharedPreferences.getString("Zipcode", "");
try {
List<Address> address = geocoder.getFromLocationName(zipcode, 1);
if ((address != null ? address.size() : 0) > 0) {
Address first = address.get(0);
mLatitude = first.getLatitude();
mLongitude = first.getLongitude();
mCurrentLocationName = getLocationAsName();
mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
.apply();
mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
.apply();
} else {
getOldZipcodeLocation();//duplicate method call
}
} catch (IOException e) {
getOldZipcodeLocation();//duplicate method call
e.printStackTrace();
}
}
Basic idea is that if they don't have internet and an exception is thrown, I want to get the old coordinates from storage. However, I also want to get the old coordinates if they are currently in a place that doesn't give them coordinates. For example, if the geocoder returns null. What bothers me is the duplicate method call in the else block and catch block. Any way to make this code cleaner? I'll take any other tips as well!
address
being null or empty. (2) Catch the null pointer exception or index out of range exception in the samecatch
block. (3) lose the "print stacktrace" despite what the average IDE thinks, there's no law saying you have to do this. // It is a matter of opinion whether this is "better"; personally I'd leave it as-is. - user16632363IOException
? - Alberto SinigagliaIOException
whenaddress
is null or empty. - user4910279