有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何修复getPostalCodenull?

我想通过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;
  }

希望能得到帮助,谢谢


共 (1) 个答案

  1. # 1 楼答案

    在邮政编码的描述中

     /**
     * 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;
    }
    

    所以,如果从最后一个位置提取的邮政编码没有成功,那么它将始终为空