Android 中的地理位置在我搜索城市(或任何东西而不是国家名称)时抛出异常适用于国家名称

Geolocation in Android throwing exception when I search for the city (or anything rather than country name) works fine with country names

当我按国家名称搜索时,它运行完美,但当我搜索城市或地点时,应用程序崩溃了。这是代码:

EditText location_tf = (EditText)findViewById(R.id.TFaddress);
        String location = location_tf.getText().toString();
        //Toast.makeText(this, location, Toast.LENGTH_SHORT).show();

        Geocoder gc = new Geocoder(this);
        List<Address> list = gc.getFromLocationName(location, 1);
        Address add = list.get(0);
        String locality = add.getLocality();
        Toast.makeText(this, locality, Toast.LENGTH_SHORT).show();

        double lat = add.getLatitude();
        double lng = add.getLongitude();

        gotoLocation(lat, lng, 4);

要获取任何城市或国家/地区的详细信息,只需使用 api 定义的 here 。 api 基本上是 - http://maps.googleapis.com/maps/api/geocode/json?address=<yourCityName>&sensor=false

基于通过此 SO 线程提供的答案

  • Android Geocoder getFromLocationName always returns null

  • Geocoder doesn't always return a value

  • Geocoder doesn't always return a value

我会说, Geocoder 并不总是 return 一个值。您需要尝试在 for 循环中发送请求 3 次。我应该能够 return 至少一次。如果不是,那么它们可能是连接问题,或者可能是其他问题,例如服务器未回复您的请求。

您需要尝试以下操作

try {
    List<Address> geoResults = geocoder.getFromLocationName("<address goes here>", 1);
    while (geoResults.size()==0) {
        geoResults = geocoder.getFromLocationName("<address goes here>", 1);
    }
    if (geoResults.size()>0) {
        Address addr = geoResults.get(0);
        myLocation.setLatitude(addr.getLatitude());
        myLocation.setLongitude(addr.getLongitude());
    }
} catch (Exception e) {
    System.out.print(e.getMessage());
}

感谢您的帮助,我发现您的回答很有帮助。 我的问题解决了,我在 MIUI 中文 ROM 上测试应用程序,在安装 MIUI 国际 ROM 后,我的代码运行得很好。

谢谢。