List <address>上的IndexOutOfBoundsException

时间:2017-01-16 16:47:09

标签: java android indexoutofboundsexception street-address

在我的Android应用中,我有以下代码:

LatLng[] branches;
String[] branchesArray = HomeActivity.branches.toArray(new String[HomeActivity.branches.size()]);

for (int i = 0; i < HomeActivity.branches.size(); i++) {
    branches[i] = getLocationFromAddress(branchesArray[i]);
}

getLocationFromAddress方法:

public LatLng getLocationFromAddress(String strAddress) {

    Geocoder coder = new Geocoder(this);
    List<Address> address;
    LatLng p1 = null;

    try {
        address = coder.getFromLocationName(strAddress, 1);

        if (address == null) {
            return null;
        }

        Address location = address.get(0);
        location.getLatitude();
        location.getLongitude();

        p1 = new LatLng((double) (location.getLatitude()), (double) (location.getLongitude()));
    } catch (IOException e) {
        Log.e("Error", e.getMessage());
    }

    return p1;
}

此代码应该创建一个LatLng数组,从一个字符串地址数组中提取。问题是每当我运行此代码时,我会在日志中获得java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0。它将第137行称为有问题的行,即这一行:

Address location = address.get(0);

我该如何解决?

2 个答案:

答案 0 :(得分:0)

getLocationFromName文档说:

  

返回Address对象列表。如果不是,则返回null或空列表   找到匹配项或没有可用的后端服务。

在您的情况下,它返回一个空列表,因此您应该添加一个额外的检查:

public LatLng getLocationFromAddress(String strAddress) {

    Geocoder coder = new Geocoder(this);
    List<Address> address;
    LatLng p1 = null;

    try {
        address = coder.getFromLocationName(strAddress, 1);

        if (address == null || address.isEmpty()) {
            return null;
        }

        Address location = address.get(0);

        p1 = new LatLng(location.getLatitude(), location.getLongitude());
    } catch (IOException e) {
        Log.e("Error", e.getMessage());
    }

    return p1;
}

答案 1 :(得分:0)

问题是你忘记用正确的大小初始化“branches”变量,这就是为什么你得到“size 0 index 0”

String[] branches = HomeActivity.branches.toArray(new String[HomeActivity.branches.size()]);