地理编码器大小的地址始终为零

时间:2017-01-18 09:10:00

标签: android location google-geocoder

我的问题是this question,我也为lat和lon做了同样的硬编码。

我得到例外以确认尺寸为

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

当我在Redmi a4上尝试相同的代码时,它工作正常,并给我1的大小,并且地理编码工作正常,返回我所有的地址。当我在联想上运行时,相同的代码就是例外。我检查了lat和lon,它们有值,当我跟踪指向我的位置时。那么我应该怎么做才能让这两款手机都可以运行该应用。 联想手机运行Android 4.4.4 Redmi运行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());

        }
    }

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

当您尝试从地址获取邮政编码,城市,国家/地区等时会发生什么情况,因为您尝试从所有邮政编码,国家,州和城市获取所有邮政编码以来,您可能无法首次接收邮件单个提供商,有时可能无法提供。相反,如果你遍历提供者,你可以在其中一个中找到它。试试这个希望它有所帮助!

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

答案 2 :(得分:0)

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

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