0

我创建了一个函数来在地理编码器的帮助下处理地址。功能是:

 public String get_address(double latitude ,double longitude)
{
    String address=null;
    if(Geocoder.isPresent())
    {
        try{
            Geocoder geocoder2 = new Geocoder(mContext, Locale.getDefault());
              List<Address> addresses;
              addresses = geocoder2.getFromLocation(latitude, longitude, 2);
               if(addresses != null) {
                     Address returnedAddress = addresses.get(0);

                     StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
                     //for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                    // strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                    //}//or

                     if(returnedAddress.getMaxAddressLineIndex() > 0){
                         strReturnedAddress.append(returnedAddress.getAddressLine(0) + ", ");
                       }

                       strReturnedAddress.append(returnedAddress.getLocality() + ", ");
                       strReturnedAddress.append(returnedAddress.getCountryName());


                     address=strReturnedAddress.toString();
                     }
                     else{
                     address="No Address returned!";
                     }
               return address;

        }
        catch(Exception e)
        {
            Log.e("MyAPP", "Reverse geo lookup failed", e);
                address="reverse geo look up failed";
             return address;
        }

    }
    else
    {
        address="Geocoder is not present";
        return address;
    }

}

然后我在每 1 分钟后从计时器编写代码调用该函数,我需要返回地址。要开发这个计时器,我使用运行方法并调度调用

私有类 mainTask 扩展 TimerTask {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            //String add=set_address();
             gps = new gpstracker(ctx);

                // check if GPS enabled
                if(gps.canGetLocation()){
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                   //String address=gps.convert_address();
                 String address2=gps.get_address(latitude, longitude);
                 address=address2;
                    // \n is for new line

                  //  Toast.makeText(getApplicationContext(), "address TWO ::"+address2, 500).show();
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();

                }

            toastHandler.sendEmptyMessage(0);
        }

    }
4

1 回答 1

0

问题可能是您正在尝试访问

Address returnedAddress = addresses.get(1);

但应该是

Address returnedAddress = addresses.get(0);

因为第一项的索引为 0。

于 2013-02-11T09:31:30.167 回答