public String getCurrentAddress() {
   StringBuilder builder = new StringBuilder();
   builder.append(street).append(", ").append(number);
   if (currentAddress.getSubLocality() != null) {
     builder.append(" - ").append(currentAddress.getSubLocality());
   }
   if (getCity() != null) {
     builder.append(", ").append(getCity());
   }
   if (currentAddress.getPostalCode() != null) {
     builder.append(", ").append(currentAddress.getPostalCode());
   }
   return builder.toString();
 }
  public String getPostalCode(Context context) {
    List<Address> addresses = getGeocoderAddress(context);

    if (addresses != null && addresses.size() > 0) {
      Address address = addresses.get(0);
      String postalCode = address.getPostalCode();

      return postalCode;
    } else {
      return null;
    }
  }
 public String getPostcode(double lat, double lon) {
   Geocoder geocode = new Geocoder(mContext, Locale.getDefault());
   try {
     List<Address> addresses = geocode.getFromLocation(lat, lon, 1);
     if (addresses != null) {
       Address fetchedAddress = addresses.get(0);
       return fetchedAddress.getPostalCode();
     }
   } catch (IOException e) {
     return "";
   }
   return "";
 }
  private void updateWithNewLocation(Location location) {
    TextView myLocationText;
    myLocationText = (TextView) findViewById(R.id.myLocationText);

    String latLongString = "No location found";
    String addressString = "No address found";

    if (location != null) {
      // Update the position overlay.
      positionOverlay.setLocation(location);
      Double geoLat = location.getLatitude() * 1E6;
      Double geoLng = location.getLongitude() * 1E6;
      GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());
      mapController.animateTo(point);

      double lat = location.getLatitude();
      double lng = location.getLongitude();
      latLongString = "Lat:" + lat + "\nLong:" + lng;

      double latitude = location.getLatitude();
      double longitude = location.getLongitude();
      Geocoder gc = new Geocoder(this, Locale.getDefault());

      if (!Geocoder.isPresent()) addressString = "No geocoder available";
      else {
        try {
          List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
          StringBuilder sb = new StringBuilder();
          if (addresses.size() > 0) {
            Address address = addresses.get(0);

            for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
              sb.append(address.getAddressLine(i)).append("\n");

            sb.append(address.getLocality()).append("\n");
            sb.append(address.getPostalCode()).append("\n");
            sb.append(address.getCountryName());
          }
          addressString = sb.toString();
        } catch (IOException e) {
          Log.d("WHEREAMI", "IO Exception", e);
        }
      }
    }

    myLocationText.setText("Your Current Position is:\n" + latLongString + "\n\n" + addressString);
  }
  public static void logAddress(String logTag, Address address) {

    int maxAddressLineIndex = address.getMaxAddressLineIndex();
    for (int i = 0; i <= maxAddressLineIndex; i++) {
      String addressLine = address.getAddressLine(i);
      Log.d(logTag, i + ":  " + addressLine);
    }

    double latitude = 0.0d;
    double longitude = 0.0d;

    boolean hasLatitude = address.hasLatitude();
    if (hasLatitude) {
      latitude = address.getLatitude();
    }
    boolean hasLongitude = address.hasLongitude();
    if (hasLongitude) {
      longitude = address.getLongitude();
    }

    String adminArea = address.getAdminArea();
    String featureName = address.getFeatureName();
    String locality = address.getLocality();
    String postalCode = address.getPostalCode();
    String premises = address.getPremises();
    String subAdminArea = address.getSubAdminArea();
    String subLocality = address.getSubLocality();
    String subThoroughfare = address.getSubThoroughfare();
    String thoroughfare = address.getThoroughfare();
    String phone = address.getPhone();
    String url = address.getUrl();

    // logValue(logTag, "latitude", hasLatitude, latitude);
    // logValue(logTag, "longitude", hasLongitude, longitude);
    //        logValue(logTag,"adminArea", adminArea);
    //        logValue(logTag,"featureName", featureName);
    //        logValue(logTag,"locality", locality);
    //        logValue(logTag,"postalCode", postalCode);
    //        logValue(logTag,"premises", premises);
    //        logValue(logTag,"subThoroughfare", subThoroughfare);
    //        logValue(logTag,"subAdminArea",subAdminArea);
    //        logValue(logTag,"subLocality", subLocality);
    //        logValue(logTag,"thoroughfare", thoroughfare);
    //        logValue(logTag,"phone", phone);
    //        logValue(logTag,"url", url);
  }
  // http://stackoverflow.com/questions/9409195/how-to-get-complete-address-from-latitude-and-longitude
  private String getAddressFromLocation(Location location) {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    List<Address> addresses = null;
    try {
      addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
    } catch (IOException e) {
      e.printStackTrace();
      // Log.e("Exception", e.getMessage());
      // Log.w("Current address location", "Cannot retrieve Address!");
    }
    if (addresses == null) return "Could not retrieve the address.";

    Address address = addresses.get(0);
    String streetAddress = address.getAddressLine(0);
    String postalCode = address.getPostalCode();
    return streetAddress + ", " + postalCode;

    //    	String streetAddress = addresses.get(0).getAddressLine(0);
    //    	String cityStateZip = addresses.get(0).getAddressLine(1);
    //    	return streetAddress + ", " + cityStateZip;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_bike_spot);
    configToolBar();
    session = new SessionManager(getApplicationContext());
    HashMap<String, String> user = session.getUserDetails();
    sessionUser = user.get(session.KEY_REGISTRATION);
    edtTextAddressName = (EditText) findViewById(R.id.editTextAddressBikeSpot);
    edtTextNumber = (EditText) findViewById(R.id.editTextAddressNumber);
    edtTextReference = (EditText) findViewById(R.id.editTextReference);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    String provider = getBestProvider();
    addListenerOnNumberPickerCapacity();
    loadBikeSpotCathegory();

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
      // TODO: Consider calling
      //    ActivityCompat#requestPermissions
      // here to request the missing permissions, and then overriding
      //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
      //                                          int[] grantResults)
      // to handle the case where the user grants the permission. See the documentation
      // for ActivityCompat#requestPermissions for more details.
      return;
    }

    location = locationManager.getLastKnownLocation(provider); // LocationManager.GPS_PROVIDER

    if (location == null) {
      location = getCurrentLocationFromUser();
    }

    if (location != null) {
      this.onLocationChanged(location);
    }

    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());

    try {
      List<Address> addresses =
          geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
      Address address = addresses.get(0);
      street = address.getAddressLine(0);
      cityState = address.getAddressLine(1);
      String[] parts = street.split(",");
      street = parts[0];
      number = address.getFeatureName();
      city = address.getLocality();
      country = address.getCountryName();
      postalCode = address.getPostalCode();
      edtTextAddressName.setText(street.toString());
      edtTextNumber.setText(number.toString());

    } catch (Exception e) {
      AlertDialog.Builder dialogo = new AlertDialog.Builder(NewBikeSpotActivity.this);
      dialogo.setTitle("Aviso!");
      dialogo.setMessage(MESSAGE_EMPTY_ADDRESS);
      dialogo.setNeutralButton(
          "OK",
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              showMapActivity();
            }
          });
      dialogo.show();
    }

    addEditTextOnEditorActionListener();

    btnSaveBikeSpotLocal = (Button) findViewById(R.id.btnSaveBikeSpot);
    btnSaveBikeSpotLocal.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {

            if ((edtTextReference.getText().toString().trim().length() == 0)
                || (edtTextAddressName.getText().toString().trim().length() == 0)
                || (edtTextNumber.getText().toString().trim().length() == 0)) {
              Toast.makeText(getApplicationContext(), MESSAGE_ERROR_NOFILLED, Toast.LENGTH_LONG)
                  .show();
            } else {
              final String fullAddressNewBikeSpot =
                  edtTextAddressName
                      .getText()
                      .toString()
                      .trim()
                      .concat(", ")
                      .concat(
                          edtTextNumber
                              .getText()
                              .toString()
                              .trim()
                              .concat(" - ")
                              .concat(cityState));
              boolean check = isBikeSpotExists(convertLocationToParseGeoPoint(location));
              boolean check2 = isBikeSpotExists(fullAddressNewBikeSpot);
              if (check || check2) {
                Toast.makeText(getApplicationContext(), MESSAGE_BIKESPOT_EXISTS, Toast.LENGTH_LONG)
                    .show();
              } else {
                saveNewBikeSpot();
                showMapActivity();
              }
            }
          }
        });

    imgBikeSpotPic = (ImageButton) findViewById(R.id.imageButtonPicture);
    ivBikeSpot = (ImageView) findViewById(R.id.imageViewBikeSpot);
    imgBikeSpotPic.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            try {
              if (isDeviceSupportCamera()) captureImage();
            } catch (Exception ex) {
              openDialogCamera();
            }
          }
        });
  }
  public void send(View v) {
    Button button = (Button) v;
    button.setText("SENT");
    EditText edittext = (EditText) findViewById(R.id.editText);
    String details = edittext.getText().toString();

    String phoneNo = "9292442978"; // Insert server phone number here. 9292442978

    gps = new GPSTracker(MainActivity.this);
    double latitude = 0.0;
    double longitude = 0.0;
    if (gps.canGetLocation()) {
      latitude = gps.getLatitude();
      longitude = gps.getLongitude();
    } else {
      // can't get location
      // GPS or Network is not enabled
      // Ask user to enable GPS/network in settings
      gps.showSettingsAlert();
    }
    String message = "swagmaster2000\n";
    String cityName;
    String countryName;
    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
    List<Address> addresses;
    try {
      addresses = gcd.getFromLocation(latitude, longitude, 1);
      cityName = addresses.get(0).getLocality();
      countryName = addresses.get(0).getCountryName();
      Address address = addresses.get(0);
      String readablehurrdurr =
          String.format(
              "%s, %s, %s, %s",
              // If there's a street address, add it
              address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
              // Locality is usually a city
              address.getLocality(),
              // The country of the address
              address.getCountryName(),
              address.getPostalCode()); // getPostalCode()
      message += (readablehurrdurr + "\n");
      message += (countryName + "\n");
      message += (cityName + "\n");
    } catch (IOException e) {
      e.printStackTrace();
    }
    message += details + "\n";
    // Toast.makeText(getApplicationContext(), message + longitude + "\n" + latitude,
    // Toast.LENGTH_LONG).show();

    if (edittext.getText().toString().equals("")) {
      Toast.makeText(
              getApplicationContext(),
              "Please describe the emergency and your location",
              Toast.LENGTH_LONG)
          .show();
      button.setText("SEND");
      return;
    }

    flag = displayGpsStatus();

    if (flag) {

      try {
        SmsManager smsManager = SmsManager.getDefault();
        PendingIntent sentPI;
        String SENT = "SMS_SENT";

        sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);

        smsManager.sendTextMessage(phoneNo, null, message, sentPI, null);
        Toast.makeText(
                getApplicationContext(),
                "Sent. Please wait for aid.", // "SMS sent. " + sentPI.toString()
                Toast.LENGTH_LONG)
            .show();
      } catch (Exception e) {
        // error lol
        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        e.printStackTrace();
      }
    } else {
      alertbox();
    }
    edittext.setText("");
  }
  /**
   * Display details for the geocoded address returned by map
   *
   * <p>This method is intended for usage with create_client_entry_address.xml
   *
   * @param activity current activity
   * @param geoAddress entity geo addresses
   */
  public static void displayGeocodedAddress(
      Activity activity, android.location.Address geoAddress) {
    final String methodName = "displayGeocodedAddress";
    // Alog.d(classTag, methodName);

    if (geoAddress == null) {
      Alog.e(methodName, "Geocoded address is not set. Cannot display address");
      return;
    }

    // Parse the geocoded Address into Mambu's Address class (5 lines)
    // final int totalLines = geoAddress.getMaxAddressLineIndex();
    // Get the whole string first
    String mapAddressString = MapActivity.getAddressString(geoAddress);
    Alog.d(methodName, "Returned overall address=" + mapAddressString);

    if (TextUtils.isEmpty(mapAddressString)) {
      // Shouldn't happen but just in case
      Alog.e(methodName, "Geocoded Address has no associated data. Nothing to display?");
      return;
    }
    // Set LatLng in the Address field from the returned Geocoded data
    EditText addressLineOneTxt = (EditText) activity.findViewById(R.id.streetAddressLine1);
    // We don't pit anything into line twp - for now
    EditText addressLineTwoTxt = (EditText) activity.findViewById(R.id.streetAddressLine2);
    EditText cityTxt = (EditText) activity.findViewById(R.id.streetAddressCity);
    EditText stateTxt = (EditText) activity.findViewById(R.id.streetAddressState);
    EditText zipPostCodeTxt = (EditText) activity.findViewById(R.id.streetAddressPostCode);
    EditText countryTxt = (EditText) activity.findViewById(R.id.streetAddressCountry);

    TextView latitudeTxt = (TextView) activity.findViewById(R.id.latitude);
    TextView longitudeTxt = (TextView) activity.findViewById(R.id.longitude);

    final int updateColor =
        activity.getResources().getColor(R.color.green_mambu_dark); // green_mambu

    double positionLatitude = geoAddress.getLatitude();
    double positionLongitude = geoAddress.getLongitude();
    Alog.d(
        methodName,
        "Displaying returned Latitude=" + positionLatitude + "\tLongitude=" + positionLongitude);
    if (latitudeTxt != null && longitudeTxt != null) {
      // Save currently displayed values and check if they changed
      BigDecimal currentLatitude = AppHelper.formatPosition(latitudeTxt.getText().toString());
      BigDecimal currentLongitude = AppHelper.formatPosition(longitudeTxt.getText().toString());
      // Alog.d(methodName, "Current: Latitude=" + currentLatitude + "\tLongitude=" +
      // currentLongitude);
      // Get the difference with new ones
      final double invPosition = -1.0f;
      double currentLatDbl = currentLatitude == null ? invPosition : currentLatitude.doubleValue();
      double currentLongDbl =
          currentLongitude == null ? invPosition : currentLongitude.doubleValue();

      // Display in Red if the difference greater than max allowed
      final double maxDif = 0.000001f;
      boolean latChanged = false;
      if (Math.abs(currentLatDbl - positionLatitude) >= maxDif) {
        latChanged = true;
      }
      boolean longChanged = false;
      if (Math.abs(currentLongDbl - positionLongitude) >= maxDif) {
        longChanged = true;
      }
      // Alog.d(methodName, "Latitude changed=" + latChanged + "\tLongitude Changed=" +
      // longChanged);

      // Display Latitude
      String latitudeStr = AppHelper.formatPosition(positionLatitude);
      latitudeTxt.setText(latitudeStr);
      int latColor = latChanged ? updateColor : defaultColor;
      int typeface = latChanged ? updateTypeface : defaultTypeface;
      latitudeTxt.setTextColor(latColor);
      latitudeTxt.setTypeface(null, typeface);

      // Display Longitude
      String longitudeStr = AppHelper.formatPosition(positionLongitude);
      longitudeTxt.setText(longitudeStr);
      int longColor = longChanged ? updateColor : defaultColor;
      typeface = longChanged ? updateTypeface : defaultTypeface;
      longitudeTxt.setTextColor(longColor);
      longitudeTxt.setTypeface(null, typeface);
    }
    // Display Google address as returned by map
    TableRow mapAddressRow = (TableRow) activity.findViewById(R.id.mapAddressRow);
    if (mapAddressRow != null) {
      mapAddressRow.setVisibility(View.VISIBLE);
    }
    TextView mapAddress = (TextView) activity.findViewById(R.id.mapAddress);
    if (mapAddress != null) {
      mapAddress.setVisibility(View.VISIBLE);
      final String googlePrefix = "Google: ";
      final String displayGeoAddress = googlePrefix + mapAddressString;
      mapAddress.setText(displayGeoAddress);
      mapAddress.setTypeface(null, Typeface.ITALIC);
    }
    // We have some address data. See whatever specific information we can get from this location

    // Get the data
    // Alog.d(methodName, "Geocoded address has lines count=" + totalLines);

    // Get the address in pieces. If any part is found - display and remove it from the original
    // address string.
    // Display what's left in line 1 and line 2

    // Make a working copy to keep track of still not parsed lines
    String remainingAddress = mapAddressString;

    // Get Country name and Country Code
    // Set Country field
    String countryName = geoAddress.getCountryName();
    String countryCode = geoAddress.getCountryCode();
    // Alog.d(methodName, "Updating Country");
    remainingAddress =
        setUpdatedValue(countryTxt, countryName, countryCode, updateColor, remainingAddress);

    // Get City field
    String locality = geoAddress.getLocality();
    String subLocality = geoAddress.getSubLocality();
    // Alog.d(methodName, "Updating City");
    remainingAddress =
        setUpdatedValue(cityTxt, locality, subLocality, updateColor, remainingAddress);

    // Get State /province
    String adminAreas = geoAddress.getAdminArea();
    String subAdminArea = geoAddress.getSubAdminArea();
    // Alog.d(methodName, "Updating State");
    remainingAddress =
        setUpdatedValue(stateTxt, adminAreas, subAdminArea, updateColor, remainingAddress);

    // Get Postal Code
    String postalCode = geoAddress.getPostalCode();
    // Alog.d(methodName, "Updating Postal Code");
    remainingAddress =
        setUpdatedValue(zipPostCodeTxt, postalCode, null, updateColor, remainingAddress);

    // We are not using Feature name
    // String featureName = geoAddress.getFeatureName();

    // See what's is the remaining string
    remainingAddress = remainingAddress == null ? "" : remainingAddress.replaceAll(",", " ");
    String[] remainingLines = remainingAddress.split("\\n");
    // int numLines = remainingLines.length;
    // Alog.d(methodName, "Remaining lines count=" + numLines);

    // Whatever was not extracted already (as City, Country, PostalCode, etc,) goes into Line 1 and
    // Line 2
    // Get Line 1 and save it as Mambu's Line 1
    String line1 = remainingLines[0].replaceAll("\\s", " ");
    line1 = line1.trim();
    // Update line 1 only if it was empty and geo address does have line 1
    boolean wasLine1Empty =
        TextUtils.isEmpty(addressLineOneTxt.getText()) && !TextUtils.isEmpty(line1);
    if (wasLine1Empty) {
      addressLineOneTxt.setText(line1);
    }
    // Define color to show line 1 is not changes but needs to be reviewed as the location changes
    final int unchangedColor = activity.getResources().getColor(R.color.dark_yellow);
    int theColor = wasLine1Empty ? updateColor : unchangedColor; // defaultColor
    int theTypeface = wasLine1Empty ? updateTypeface : updateTypeface; // defaultTypeface

    addressLineOneTxt.setTextColor(theColor);
    addressLineOneTxt.setTypeface(null, theTypeface);

    // Remove line 1 form the original string
    if (!TextUtils.isEmpty(line1)) {
      remainingAddress = remainingAddress.replace(line1, "");
    }

    // If anything still remaining, put it in Mambu's Line 2
    remainingAddress = remainingAddress.replace("\\s", " ");
    remainingAddress = remainingAddress.replace("\n", "");
    String line2 = remainingAddress.trim();
    if (line2.length() > 0) {
      // Do Not set line 2 for now
      // addressLineTwoTxt.setText(line2);
    }
    // Set the same colors as for line 1 .
    addressLineTwoTxt.setTextColor(theColor);
    addressLineTwoTxt.setTypeface(null, theTypeface);

    // Alog.d(methodName, "Country Name=" + countryName + " Country code=" + countryCode + " Postal
    // code="
    // + postalCode + "  Admin area=" + adminAreas + " Feature Name=" + featureName + " Locality=" +
    // locality
    // + "  Sub Locality=" + subLocality);

    Alog.d(methodName, "Remaining  address=" + remainingAddress);
    // Alog.d("Line1 =" + line1 + "\nLine 2=" + line2);

  }
    /**
     * Get a Geocoder instance, get the latitude and longitude look up the address, and return it
     *
     * @params params One or more Location objects
     * @return A string containing the address of the current location, or an empty string if no
     *     address can be found, or an error message
     */
    @Override
    protected String doInBackground(Location... params) {

      Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
      // Get the current location from the input parameter list
      Location loc = params[0];
      // Create a list to contain the result address
      List<Address> addresses = null;
      try {
        /*
         * Return 1 address.
         */
        addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
      } catch (IOException e1) {
        Log.e("LocationSampleActivity", "IO Exception in getFromLocation()");
        e1.printStackTrace();
        return ("IO Exception trying to get address");
      } catch (IllegalArgumentException e2) {
        // Error message to post in the log
        String errorString =
            "Illegal arguments "
                + Double.toString(loc.getLatitude())
                + " , "
                + Double.toString(loc.getLongitude())
                + " passed to address service";
        Log.e("LocationSampleActivity", errorString);
        e2.printStackTrace();
        return errorString;
      }
      // If the reverse geocode returned an address
      if (addresses != null && addresses.size() > 0) {
        // Get the first address
        Address address = addresses.get(0);
        /*
         * Format the first line of address (if available), city, and
         * country name.
         */

        String addressMessage = address.getAddressLine(0) + " " + address.getAddressLine(1);
        String addressText =
            String.format(
                "%s, %s, %s, %s",
                // If there's a street address, add it
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                // Locality is usually a city
                address.getLocality(),
                address.getPremises(),
                // The country of the address
                address.getCountryName());

        // streetAddress = address.getAddressLine(1);
        // Return the text

        streetadd =
            address.getAddressLine(0)
                + ","
                + address.getAddressLine(1)
                + ","
                + address.getCountryName();

        Log.e(
            "TAG",
            address.getAddressLine(0)
                + ""
                + address.getCountryCode()
                + " "
                + address.getCountryName());
        countryId = address.getCountryCode();
        country = address.getCountryName();
        adlevel1 = address.getAdminArea();
        adlevel2 = address.getSubAdminArea();
        // streetadd = address.getAddressLine(0)
        // + address.getAddressLine(1);
        locality = address.getLocality();
        postalcode = address.getPostalCode();

        Log.e("check country code", "" + address.getCountryCode());
        Log.e("Locale", "" + address.getLocale());
        Log.e("Maxaddlineindex", "" + address.getMaxAddressLineIndex());
        Log.e("subadminarea", "" + address.getSubAdminArea());
        Log.e("addres line", "" + address.getAddressLine(0));
        Log.e("addres line 1", "" + address.getAddressLine(1));
        Log.e("adminarea", "" + address.getAdminArea());
        Log.e("featurename", "" + address.getFeatureName());
        Log.e("adminarea", "" + address.getAdminArea());
        Log.e("Locality", "" + address.getLocality());
        Log.e("premises", "" + address.getPremises());
        Log.e("postalcode", "" + address.getPostalCode());
        Log.e("sublocality", "" + address.getSubLocality());
        Log.e("extras", "" + address.getExtras());

        Log.e("back country", "" + country);

        Log.e("streetAddress", "" + streetadd);
        return addressMessage;
      } else {
        return "No address found";
      }
    }