Fatih Ozcan Fatih Ozcan - 1 year ago 74
Android Question

Geocoder returns an address with zero length

Geocoder was working fine until today. It started to return String with 0 length.
Note: This is not a duplicate of Geocoder threads, i used intent service and AsyncTask to get it before starting the thread(and AsyncTask approach was working fine over 8 months), checked this code and new code from Google with FusedLocationProviderClient(this is offical code) it also returns string with zero length.This link from official Android page shows how to get it with intent service.

I get full address on Android 5.1 but on Android 7.1 it returns an address with length zero.

Code i used to use and worked fine until today.

private void getAddressFromCoordinates() {

new AsyncTask<Void, String, Void>() {

@Override
protected Void doInBackground(Void... params) {

try {
addresses.clear();
addresses.addAll(geocoder.getFromLocation(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude(), 1));


} catch (IOException e) {
e.printStackTrace();
showToastAsync(getString(R.string.activity_loc_no_location_info));
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
showToastAsync("Invalid latitude or longitude values");
}

// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
showToastAsync(getString(R.string.activity_loc_no_address_is_found));
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}

addressInfo = TextUtils.join(System.getProperty("line.separator"), addressFragments);
addressSingleLine = LocationActivity.addressInfo.replaceAll("[\r\n]+", " ");
}
return null;
}

}.execute();
}


Answer is to add
=
to for loop to not retreive an address with zero length on Android 7. You don't need to do this on some versions. Also code on Google referenced Github pages is missing =. That's why i was not able to find the reason why.

Answer Source

The problem is this line:

for (int i = 0; i < address.getMaxAddressLineIndex(); i++)

It must be : for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) Because getMaxAddressLineIndex returns the largest index.

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