I have the following class which returns a coordinate depending on the 
street name I enter.

public class CoordinateViaStreetNameFinder {
    private Geocoder geocoder;

    public CoordinateViaStreetNameFinder() {
        geocoder = new Geocoder(ApplicationContext.getAppContext(), 
Locale.GERMAN);
    }
    
    public Coordinate find(String streetName, String streetNr) throws 
IOException  {
        String searchPattern = streetName + ", " + streetNr + ", AT";
        
        List<Address> addresses = 
geocoder.getFromLocationName(searchPattern, 1);
        
        if (addresses == null || addresses.size() < 1)  {
            return null;
        }
        
        return new Coordinate(addresses.get(0).getLongitude(), 
addresses.get(0).getLatitude());
    }
}

This works for valid street names. When I enter an invalid street name like 
"foobar street", I run into this exception, when the app tries to execute 
the if statement:

java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0
at java.util.ArrayList.get(ArrayList.java:341)

I'm a bit confused since getFromLocationName should return by definition 
null or empty list. How does this error come then? I invoke this method in 
a Android JUnit test:
This test works:

    public void testValidResult() throws IOException {
        CoordinateViaStreetNameFinder coordinateViaStreetNameFinder = new 
CoordinateViaStreetNameFinder();
        
        Coordinate coordinate = 
coordinateViaStreetNameFinder.find("stephansplatz", "1");
        
        assertEquals(16, (int)(coordinate.getLongitude()));
        assertEquals(48, (int)(coordinate.getLatitude()));
    }

This test produces the error.
    
    public void testInvalidResult() throws IOException {
        CoordinateViaStreetNameFinder coordinateViaStreetNameFinder = new 
CoordinateViaStreetNameFinder();
        
        Coordinate coordinate = coordinateViaStreetNameFinder.find("foobar 
street", "1");
        
        assertNull(coordinate);
    }

What's wrong here?

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to