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

Android中的地理定位在我搜索城市(或任何东西,而不是国家名称)时抛出异常,适用于国家名称,android,google-geocoder,Android,Google Geocoder,当我按国家名称搜索时,它工作得很好,但当我搜索城市或地方时,应用程序崩溃了。代码如下: EditText location_tf = (EditText)findViewById(R.id.TFaddress); String location = location_tf.getText().toString(); //Toast.makeText(this, location, Toast.LENGTH_SHORT).show(); Geoco

当我按国家名称搜索时,它工作得很好,但当我搜索城市或地方时,应用程序崩溃了。代码如下:

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即可。空气污染指数基本上是-http://maps.googleapis.com/maps/api/geocode/json?address=&sensor=false

基于本报告提供的答案

我想说,, 地理编码器并不总是返回值。您需要在for循环中尝试发送请求3次。我至少能回来一次。如果不是,则可能是连接问题,也可能是其他问题,如服务器不响应您的请求

你需要试试下面的方法

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之后,我的代码工作得很好


多谢各位

发布异常跟踪和您的问题