【问题标题】:addresses from Geocoder size is always zero来自地理编码器大小的地址始终为零
【发布时间】:2017-01-18 09:10:00
【问题描述】:

我遇到了 this question 的问题,我也对 lat 和 lon 进行了相同的硬编码。

我得到异常确认大小为

Exception for the locationjava.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

当我在 Redmi a4 上尝试相同的代码时,它运行良好,大小为 1,地理编码也运行良好,将所有地址返回给我。当我在联想上运行相同的代码时,它给出了异常。我检查了纬度和经度,它们的值在我追踪时指向我的位置。那么我应该怎么做才能让应用程序在两部手机上运行。 运行 Android 4.4.4 的联想手机 红米运行 6.0.0

if(lat != null && lon !=null) {
        try{

       Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(this, Locale.getDefault());
        addresses = geocoder.getFromLocation(dlat, dlon, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
        System.out.println("this is the size of address size"+addresses.size());
         String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();
        String postalCode = addresses.get(0).getPostalCode();
        String knownName = addresses.get(0).getFeatureName();
        complete_address=address + "_" + city + "_" + address + "_" + postalCode + "_" + knownName + "_" + country;
        txtOutputLat.setText(complete_address);
        txtOutputLon.setText("Map Address");
    }
        catch(Exception e)
        {
            System.out.println("Exception for the location"+e.toString());

        }
    }

【问题讨论】:

  • 你的纬度长得正确吗?
  • 是的,在我的应用程序中,当我单击按钮时,它会打开 waze 上的 lat lan,它工作正常。此外,当我在网上追踪它们时,它会显示我所在的位置。

标签: android location google-geocoder


【解决方案1】:

创建此类并复制代码,这对我来说非常有效,这也可以在后台运行并从 ANR 对话框中停止主线程

 import android.content.Context;
 import android.location.Address;
 import android.location.Geocoder;
 import android.os.AsyncTask;

 import java.io.IOException;
 import java.util.List;
 import java.util.Locale;


public class GetLocationAsync extends AsyncTask<String, Void, String> {
private String fulladdress = "";
private String smallAddress = "";
private String city = "";
private String state = "";
private String country = "";
private String zipcode = "";
private String placeName = "";

private AsyncResponse asyncResponseDelegate = null;
private   double x, y;
private Context context;

public interface AsyncResponse {
    void onProcessFinished(String fulladdress, String smallAddress, String state, String city, String country, String zipCode, String placeName);
}

public GetLocationAsync(double latitude, double longitude, final Context context, AsyncResponse asyncResponse) {
    x = latitude;
    y = longitude;
    this.context = context;
    this.asyncResponseDelegate = asyncResponse;
}

@Override
protected void onPreExecute() {
}

@Override
protected String doInBackground(String... params) {
    Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
    try {
        List<Address> addressList = geocoder.getFromLocation(x, y, 1);
        StringBuilder sb = new StringBuilder();
        if (addressList != null && addressList.size() > 0) {
            Address address = addressList.get(0);
            fulladdress = "";
            smallAddress = "";
            placeName = "";
            if (sb.append(address.getAddressLine(0)) != null) {
                smallAddress = address.getAddressLine(0);
                fulladdress = smallAddress;
            }
            if (address.getLocality() != null) {
                city = address.getLocality();
                if (!fulladdress.contains(city))
                    fulladdress = fulladdress + " " + city;
            }
            if (address.getFeatureName() != null) {
                placeName = address.getFeatureName();
            }
            if (address.getAdminArea() != null) {
                state = address.getAdminArea();
                if (!fulladdress.contains(state))
                    fulladdress = fulladdress + " " + state;
            }
            if (address.getPostalCode() != null) {
                zipcode = address.getPostalCode();
                if (!fulladdress.contains(zipcode))
                    fulladdress = fulladdress + " " + zipcode;
            }
            if (address.getCountryName() != null) {
                country = address.getCountryName();
                if (!fulladdress.contains(country))
                    fulladdress = fulladdress + " " + country;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(String result) {
    try {
        if (fulladdress != null && !fulladdress.isEmpty()) {
            asyncResponseDelegate.onProcessFinished(fulladdress, smallAddress, state, city, country, zipcode, placeName);
        } else {
            asyncResponseDelegate.onProcessFinished("", "", "", "", "", "", "");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 }

调用这个类

  GetLocationAsync locationAsync = new GetLocationAsync(latitude,
                                        longitude, getActivity(), new    GetLocationAsync.AsyncResponse() {
                                    @Override
                                    public void onProcessFinished(String fulladdress, String smallAddress, String state, String city, String country, String zipCode, String placeName) {
                                        etAddress.setText(fulladdress);
                                    }
                                });
                                locationAsync.execute();

【讨论】:

    【解决方案2】:

    当您尝试仅从地址获取邮政编码、城市、国家/地区等时,您可能不会第一次收到它,因为它试图从该地址获取所有邮政编码、国家/地区、州和城市单个提供商,有时可能不可用。相反,如果您遍历提供者,您可能会在其中之一中找到它。试试这个希望它有帮助!

                   List<Address> addresses  = null;
                        try {
                            addresses =geocoder.getFromLocation(latitude,longitude, 5);
    
                            if (addresses.size() > 0) {
    
                                zipCode = addresses.get(0).getPostalCode();
                                city = addresses.get(0).getLocality();
                                country = addresses.get(0).getCountryName();
                                state = addresses.get(0).getAdminArea();
                                address = addresses.get(0).getAddressLine(0);
                                knownName = addresses.get(0).getFeatureName();
    
    
                                //if 1st provider does not have data, loop through other providers to find it.
                                int count = 0;
                                while ( count < addresses.size()) {
                                    zipCode = addresses.get(count).getPostalCode();
                                        city= addresses.get(count).getLocality();
                                country = addresses.get(count).getCountryName();
                                state = addresses.get(count).getAdminArea();
                                 address = addresses.get(count).getAddressLine(0);
                                knownName = addresses.get(count).getFeatureName();
    
    
    
    
    
    
                                    count++;
                                }
                            }
    
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
    

    【讨论】:

    • 事情是我总是把地址设为零,所以它永远不会在联想上移动那个部分,在红米上它工作得很好。
    【解决方案3】:

    在调用地理编码器之前检查互联网连接。

        if(isConnectingToInternet(getContext()){
          //write your code of calling geocoder
         }
    
    
       public boolean isConnectingToInternet(Context context) {
        try {
            if (context != null) {
                ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (connectivity != null) {
                    NetworkInfo[] info = connectivity.getAllNetworkInfo();
                    if (info != null)
                        for (int i = 0; i < info.length; i++)
                            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                return true;
                            }
                }
            }
        } catch (Exception e) {
           e.printStacktrace   
        }
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-25
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多