首页 > 解决方案 > 如何修复 getPostalCode-null?

问题描述

我想通过address获取我手机定位到的地址的邮编,但是返回null。

手机已开启GPS,可获取位置信息,但无法获取邮政编码。

  /**
   * Convert Location to Address
   * @param location Latitude and Longitude
   * @return
   */
  private String getAddress(Location location) {
      // result
      List<Address> result = null;
      String addressLine = "";// address
      try {
          if (location != null) {
              Geocoder gc = new Geocoder(mContext, Locale.getDefault());
              result = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
          }
      } catch (Exception e) {
          e.printStackTrace();
      }

      if (result != null && result.get(0) != null) {
          // success
          Address address = result.get(0);
          addressLine = address.getAddressLine(0);


          String postalCode = address.getPostalCode();

          LogUtil.e(Fields.println.Location, "address=======" + addressLine+"===postalCode==="+postalCode);
          LogUtil.e(Fields.println.Location, "result=======" + result.toString());
      }

      return addressLine;
  }

希望得到帮助,谢谢!

标签: javaandroidpostal-code

解决方案


在邮政编码的描述中

 /**
 * Returns the postal code of the address, for example "94110",
 * or null if it is unknown.
 */
public String getPostalCode() {
    return mPostalCode;
}

/**
 * Sets the postal code of the address to the given String, which may
 * be null.
 */
public void setPostalCode(String postalCode) {
    mPostalCode = postalCode;
}

因此,如果未成功从最后一个位置获取邮政编码,则它将始终为空。


推荐阅读