Java 列表上的IndexOutOfBoundsException<;地址>;

Java 列表上的IndexOutOfBoundsException<;地址>;,java,android,indexoutofboundsexception,street-address,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(branche

在我的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]);
}

如何修复此问题?

getLocationFromName
文档说明:

返回地址对象的列表。如果没有,则返回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;
}
public LatLng getLocationFromAddress(字符串){
地理编码器=新地理编码器(本);
名单地址;
LatLng p1=null;
试一试{
地址=编码者。getFromLocationName(1);
if(address==null | | address.isEmpty()){
返回null;
}
地址位置=地址。获取(0);
p1=新车床(location.getLatitude(),location.getLongitude());
}捕获(IOE异常){
Log.e(“Error”,e.getMessage());
}
返回p1;
}

问题在于您忘记了用正确的大小初始化“branchs”变量,这就是为什么您会得到“size 0 index 0”


为什么不直接使用
HomeActivity.branchs.get(i)
而不是
branchesArray[i]
?您认为
location.getLatitude()怎么样
location.getLongitude()branchesArray
更改为
branchs
。这是什么意思?当初始化字符串[]分支时,循环会超过索引0;你喜欢说我正在创建一个空数组,其大小为0。数组与列表不同,在不知道前面的大小的情况下,可以使用该列表添加不确定的项。另一方面,数组必须使用定义的大小创建,因此String Branchs[]是数组大小0(空),String[]Branchs=new String[20]是一个可以容纳20个项而不存在IndexAutofBound问题的数组。这就是为什么当循环到达1或(在您的情况下,我猜是0)Branchs[1]=getLocationFromAddress(branchesArray[1]);它抛出了一个错误,因为您告诉我分支变量的最大长度是1,甚至是0)问题是我不需要它返回null。我需要它返回一个
LatLng
对象。
Address location = address.get(0);
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;
}
String[] branches = HomeActivity.branches.toArray(new String[HomeActivity.branches.size()]);