簡體   English   中英

列表上的 IndexOutOfBoundsException<Address>

[英]IndexOutOfBoundsException on List<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 in the log。 它將第 137 行稱為有問題的行,即這一行:

Address location = address.get(0);

我該如何解決?

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

問題是你忘記用正確的大小初始化“分支”變量,這就是為什么你得到“大小 0 索引 0”

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM