2017-01-16 110 views
-1

在我的Android应用程序,我有这样的代码:IndexOutOfBoundsException异常的名单<Address>

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); 

我该如何解决这个问题?

+0

为什么不只是使用'HomeActivity.branches.get(i)'而不'branchesArray [i]'? –

+0

你觉得'location.getLatitude();'和'location.getLongitude();'是做什么的? –

回答

0

getLocationFromName文件说:

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

你的情况,它返回一个空列表,所以你应该添加一个额外的检查:

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; 
} 
+0

问题是我不需要它返回null。我需要它返回一个'LatLng'对象。 – Ido

+0

如果您没有坐标,则无法返回LatLng对象.... –

0

的probleme是您忘了初始化“分支”变量与正确的尺寸,这就是为什么你越来越“大小0索引0”

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

我不明白您的答案。您只是从我的代码中复制了该行,但将'branchesArray'更改为'branches'。什么意思? – Ido

+0

你的循环在索引0之上并且初始化了String []分支;你喜欢说我正在创建一个空阵列女巫的大小是0阵列不像列表中,你可以追加不确定的项目而不知道未来的大小。另一方面,数组必须创建一个定义的大小,所以字符串branches []是一个数组大小为0(空),并且String [] branches = new String [20]是一个数组,可以容纳20个项目而不会有indexOutOfBound问题 – thunder413

+0

这就是为什么当你循环到达1或(在你的情况下,我猜0) branches [1] = getLocationFromAddress(branchesArray [1]); 它抛出一个错误,因为你确实告诉你最大长度分支变种是1或甚至0) – thunder413

相关问题