0

我正在尝试定位一对经纬度。当没有例外时,它的效果很好。

日志猫:

GLS Failed With Status 20

代码如下:

//TAG GEOCODING METHOD
    public Address getAddressForLocation(Context context, Location location) throws IOException {

     Address a = null;
     try{
        if (location == null) {
            a=null;
        }
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        int maxResults = 1;


        Geocoder gc = new Geocoder(context, Locale.getDefault());
        List<Address> addresses = gc.getFromLocation(latitude, longitude, maxResults);


        if (addresses.size() == 1) {
            a=addresses.get(0);
        } else {
            a=null;
        }
     }catch (Exception e){
      Log.w("EXCEPTON!", "Exception Caught in geocode");
      a=null;
     }
     return a;
    }

该调用也包含在 try/catch 块中。

 @Override//TAG On Location Changed
    public void onLocationChanged(Location arg0) {
//SET ALL VALUES
            dlat = arg0.getLatitude();
            dlon = arg0.getLongitude();

            delev = arg0.getAltitude() * 3.2808399;
            delev = round(delev, 2);

//GET THE ADDRESS
              try {
                addy = getAddressForLocation(this,arg0);
               } catch (Exception e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
                }
                _lastaddy = _addy;
                //DISPLAY ALL INFORMATION
                 _addy = addy.getAddressLine(0);  
                    LONGBOX.setText(String.valueOf(dlon));
                   LATBOX.setText(String.valueOf(dlat));
if(_addy!=_lastaddy){
                      ADDRESS.setText(_addy);
}

                  }

logcat 的其余部分如下。对此的任何帮助都会很棒。我无法捕捉到这个异常,并且盯着这段代码这么久,仍然不知道我做错了什么。

日志猫:

LocationMasfClient  reverseGeocode(): GLS failed with status 20
AndroidRuntime      Shutting down VM
dalvikvm            threadid=1: thread exiting with uncaught exception (group=0x400208b0)
AndroidRunTime      FATAL EXCEPTION: main
AndroidRunTime      java.lang.NullPointerException
4

1 回答 1

1

我认为问题在于您捕获了异常,但随后返回(并最终尝试使用)一个空地址对象getAddressForLocation

catch (Exception e){
      Log.w("EXCEPTON!", "Exception Caught in geocode");
      a=null;
     }
     return a;

因此,此时 addy 将为空:

addy = getAddressForLocation(this,arg0);

当你去使用addy时,你会得到一个NullPointerException

_addy = addy.getAddressLine(0);  

您要么需要在使用之前检查 addy 是否为 null,要么将Exception您捕获的内容扔进去getAddressForLocation并处理它onLocationChange

于 2011-01-24T01:00:21.050 回答