Example usage for android.location Geocoder getFromLocation

List of usage examples for android.location Geocoder getFromLocation

Introduction

In this page you can find the example usage for android.location Geocoder getFromLocation.

Prototype

public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException 

Source Link

Document

Returns an array of Addresses that are known to describe the area immediately surrounding the given latitude and longitude.

Usage

From source file:com.binomed.showtime.android.util.CineShowtimeRequestManage.java

private static Location manageLocation(Geocoder geocoder, String cityName, URLBuilder andShowtimeUriBuilder,
        Double latitude, Double longitude) throws IOException {
    Location originalPlace = null;
    if (geocoder != null) {
        if (cityName != null) {
            try {
                cityName = URLDecoder.decode(cityName, CineShowTimeEncodingUtil.getEncoding());
            } catch (Exception e) {
                Log.e(TAG, "Error during encode", e);
            }//  ww w .j a  va2  s.  co m
            List<Address> addressList = geocoder.getFromLocationName(cityName, 1);
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getPostalCode() != null)) {
                    cityName += " " + addressList.get(0).getPostalCode();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }
                originalPlace = new Location("GPS");
                originalPlace.setLongitude(addressList.get(0).getLongitude());
                originalPlace.setLatitude(addressList.get(0).getLatitude());
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
        }
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            List<Address> addressList = geocoder.getFromLocation(longitude, latitude, 1);
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getPostalCode() != null)) {
                    cityName += " " + addressList.get(0).getPostalCode();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }
                originalPlace = new Location("GPS");
                originalPlace.setLongitude(addressList.get(0).getLongitude());
                originalPlace.setLatitude(addressList.get(0).getLatitude());
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LAT //
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(latitude));
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LONG//
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(longitude));
        }
    } else {
        if (cityName != null) {
            try {
                cityName = URLDecoder.decode(cityName, CineShowTimeEncodingUtil.getEncoding());
            } catch (Exception e) {
                Log.e(TAG, "error during decoding", e);
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
        }
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LAT //
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(latitude));
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LONG//
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(longitude));
        }
    }

    return originalPlace;
}

From source file:org.egov.android.view.activity.CreateComplaintActivity.java

public String getCurrentLocation(double lat, double lng) {

    String cityName = "";

    if (lat == 0 && lng == 0) {
        return "";
    }//from   w ww  .j  av  a2s. c om

    Geocoder geocoder = new Geocoder(CreateComplaintActivity.this, Locale.getDefault());
    List<Address> addresses;
    try {
        addresses = geocoder.getFromLocation(lat, lng, 1);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);
            cityName = address.getThoroughfare();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return cityName;
}

From source file:com.instiwork.RegistrationFacebookActivity.java

private void enableMyLocation() {
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        PermissionUtils.requestPermission(this, MY_PERMISSIONS_REQUEST_READ,
                android.Manifest.permission.ACCESS_FINE_LOCATION, false);
    } else {/*from   w  ww .j a  va2s .  c  o  m*/
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            LOCATION_LATITUDE = "" + mLastLocation.getLatitude();
            LOCATION_LONGITUDE = "" + mLastLocation.getLongitude();

            try {
                Geocoder geocoder = new Geocoder(RegistrationFacebookActivity.this, Locale.getDefault());
                List<Address> addresses = geocoder.getFromLocation(mLastLocation.getLatitude(),
                        mLastLocation.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

                currentCountry = "" + addresses.get(0).getCountryName();

            } catch (Exception e) {
                e.printStackTrace();
            }

            getCountryList();
        }
    }
}

From source file:com.instiwork.RegistrationFacebookActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode != MY_PERMISSIONS_REQUEST_READ) {
        return;/*from  w  w  w.  j a  v a 2  s.c  o  m*/
    }

    try {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            LOCATION_LATITUDE = "" + mLastLocation.getLatitude();
            LOCATION_LONGITUDE = "" + mLastLocation.getLongitude();

            try {
                Geocoder geocoder = new Geocoder(RegistrationFacebookActivity.this, Locale.getDefault());
                List<Address> addresses = geocoder.getFromLocation(mLastLocation.getLatitude(),
                        mLastLocation.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

                currentCountry = "" + addresses.get(0).getCountryName();

            } catch (Exception e) {
                e.printStackTrace();
            }

            getCountryList();
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

From source file:no.ntnu.idi.socialhitchhiking.map.MapActivityCreateOrEditRoute.java

/** gotLocation(andoid.location.Location location)
 * helping method for the gpsClicked method
 * fills the acFrom {@link AutoCompleteTextView} field with the gps information
 * @param location/*from ww  w .ja v a 2  s .  c o m*/
 */
public void gotLocation(android.location.Location location) {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        acFrom.setText(addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1));
    } catch (IOException e) {
        Toast.makeText(this, "Problem with GPS, try restarting your device", Toast.LENGTH_LONG).show();
    }
    loadingDialog.dismiss();
}

From source file:com.binomed.showtime.android.util.CineShowtimeRequestManage.java

public static NearResp searchTheatersOrMovies(Context context, Double latitude, Double longitude,
        String cityName, String movieName, String theaterId, int day, int start, String origin,
        String hourLocalized, String minutesLocalized) throws Exception {

    URLBuilder andShowtimeUriBuilder = new URLBuilder(CineShowTimeEncodingUtil.convertLocaleToEncoding());
    andShowtimeUriBuilder.setProtocol(HttpParamsCst.BINOMED_APP_PROTOCOL);
    andShowtimeUriBuilder.setAdress(getAppEngineUrl(context));
    andShowtimeUriBuilder.completePath(HttpParamsCst.BINOMED_APP_PATH);
    andShowtimeUriBuilder/*from w ww  . j a v  a  2 s  .c  o m*/
            .completePath(((movieName != null) && (movieName.length() > 0)) ? HttpParamsCst.MOVIE_GET_METHODE
                    : HttpParamsCst.NEAR_GET_METHODE);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LANG, Locale.getDefault().getLanguage());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_OUTPUT, HttpParamsCst.VALUE_XML);
    // andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_ZIP, HttpParamsCst.VALUE_TRUE);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_IE, CineShowTimeEncodingUtil.getEncoding());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_OE, CineShowTimeEncodingUtil.getEncoding());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_CURENT_TIME,
            String.valueOf(Calendar.getInstance().getTimeInMillis()));
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_TIME_ZONE, TimeZone.getDefault().getID());
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_HOUR_LOCALIZE, hourLocalized);
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MIN_LOCALIZE, minutesLocalized);

    if (theaterId != null) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_THEATER_ID //
                , theaterId);
    }
    if (day > 0) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_DAY //
                , String.valueOf(day));
    }
    if (start > 0) {
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_START //
                , String.valueOf(start));
    }
    String countryCode = Locale.getDefault().getCountry();

    Geocoder geocoder = CineShowtimeFactory.getGeocoder();
    Location originalPlace = null;
    if (geocoder != null) {
        if (cityName != null) {
            try {
                cityName = URLDecoder.decode(cityName, CineShowTimeEncodingUtil.getEncoding());
            } catch (Exception e) {
                Log.e(TAG, "error during decoding", e);
            }
            List<Address> addressList = null;
            try {
                addressList = geocoder.getFromLocationName(cityName, 1);
            } catch (Exception e) {
                Log.e(TAG, "error Searching cityName :" + cityName, e);
            }
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                // if (addressList.get(0).getLocality() != null &&
                // addressList.get(0).getPostalCode() != null) {
                // cityName += " " + addressList.get(0).getPostalCode();
                // }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }

                originalPlace = new Location("GPS");
                originalPlace.setLongitude(addressList.get(0).getLongitude());
                originalPlace.setLatitude(addressList.get(0).getLatitude());

                countryCode = addressList.get(0).getCountryCode();
            }
            if (cityName != null) {
                andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
            }
        }
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            List<Address> addressList = null;
            try {
                addressList = geocoder.getFromLocation(latitude, longitude, 1);
            } catch (Exception e) {
                Log.e(TAG, "error Searching latitude, longitude :" + latitude + "," + longitude, e);
            }
            if ((addressList != null) && !addressList.isEmpty()) {
                if (addressList.get(0).getLocality() != null) {
                    cityName = addressList.get(0).getLocality();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getPostalCode() != null)) {
                    cityName += " " + addressList.get(0).getPostalCode();
                }
                if ((addressList.get(0).getLocality() != null)
                        && (addressList.get(0).getCountryCode() != null)) {
                    cityName += ", " + addressList.get(0).getCountryCode();
                }
                originalPlace = new Location("GPS");
                originalPlace.setLongitude(addressList.get(0).getLongitude());
                originalPlace.setLatitude(addressList.get(0).getLatitude());

                countryCode = addressList.get(0).getCountryCode();
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LAT //
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(latitude));
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LONG//
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(longitude));
            if (cityName != null) {
                andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
            }
        }
    } else {
        if (cityName != null) {
            try {
                cityName = URLDecoder.decode(cityName, CineShowTimeEncodingUtil.getEncoding());
            } catch (Exception e) {
                Log.e(TAG, "error during decoding", e);
            }
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_PLACE, cityName);
        }
        if ((latitude != null) && (longitude != null) && ((latitude != 0) && (longitude != 0))) {
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LAT //
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(latitude));
            andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_LONG//
                    , AndShowtimeNumberFormat.getFormatGeoCoord().format(longitude));
        }
    }
    andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_COUNTRY_CODE, countryCode);

    if (movieName != null) {
        try {
            movieName = URLDecoder.decode(movieName, CineShowTimeEncodingUtil.getEncoding());
        } catch (Exception e) {
            Log.e(TAG, "error during decoding", e);
        }
        andShowtimeUriBuilder.addQueryParameter(HttpParamsCst.PARAM_MOVIE_NAME, movieName);
    }

    String uri = andShowtimeUriBuilder.toUri();
    Log.i(TAG, "send request : " + uri); //$NON-NLS-1$
    HttpGet getMethod = CineShowtimeFactory.getHttpGet();
    getMethod.setURI(new URI(uri));
    HttpResponse res = CineShowtimeFactory.getHttpClient().execute(getMethod);

    XMLReader reader = CineShowtimeFactory.getXmlReader();
    ParserNearResultXml parser = CineShowtimeFactory.getParserNearResultXml();
    reader.setContentHandler(parser);
    InputSource inputSource = CineShowtimeFactory.getInputSource();
    // inputSource.setByteStream(new GZIPInputStream(res.getEntity().getContent()));
    inputSource.setByteStream(res.getEntity().getContent());

    reader.parse(inputSource);

    NearResp resultBean = parser.getNearRespBean();
    resultBean.setCityName(cityName);

    return resultBean;
}

From source file:com.mibr.android.intelligentreminder.INeedToo.java

public List<Address> getAddressList(Location location) {
    if (addressList == null || addressList.size() == 0) {
        Geocoder g = new Geocoder(getApplicationContext());
        try {//from   www .ja v  a2s. c  o  m
            addressList = g.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        } catch (Exception eieio) {
        }
    }
    return addressList;
}

From source file:org.telegram.ui.ThemeActivity.java

private void updateSunTime(Location lastKnownLocation, boolean forceUpdate) {
    LocationManager locationManager = (LocationManager) ApplicationLoader.applicationContext
            .getSystemService(Context.LOCATION_SERVICE);
    if (Build.VERSION.SDK_INT >= 23) {
        Activity activity = getParentActivity();
        if (activity != null) {
            if (activity.checkSelfPermission(
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION }, 2);
                return;
            }//from   w  w w . j  a va 2 s.c o  m
        }
    }
    if (getParentActivity() != null) {
        if (!getParentActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) {
            return;
        }
        try {
            LocationManager lm = (LocationManager) ApplicationLoader.applicationContext
                    .getSystemService(Context.LOCATION_SERVICE);
            if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setMessage(LocaleController.getString("GpsDisabledAlert", R.string.GpsDisabledAlert));
                builder.setPositiveButton(
                        LocaleController.getString("ConnectingToProxyEnable", R.string.ConnectingToProxyEnable),
                        (dialog, id) -> {
                            if (getParentActivity() == null) {
                                return;
                            }
                            try {
                                getParentActivity().startActivity(
                                        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            } catch (Exception ignore) {

                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
                return;
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    }
    try {
        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
    if (lastKnownLocation == null || forceUpdate) {
        startLocationUpdate();
        if (lastKnownLocation == null) {
            return;
        }
    }
    Theme.autoNightLocationLatitude = lastKnownLocation.getLatitude();
    Theme.autoNightLocationLongitude = lastKnownLocation.getLongitude();
    int time[] = SunDate.calculateSunriseSunset(Theme.autoNightLocationLatitude,
            Theme.autoNightLocationLongitude);
    Theme.autoNightSunriseTime = time[0];
    Theme.autoNightSunsetTime = time[1];
    Theme.autoNightCityName = null;
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    Theme.autoNightLastSunCheckDay = calendar.get(Calendar.DAY_OF_MONTH);
    Utilities.globalQueue.postRunnable(() -> {
        String name;
        try {
            Geocoder gcd = new Geocoder(ApplicationLoader.applicationContext, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(Theme.autoNightLocationLatitude,
                    Theme.autoNightLocationLongitude, 1);
            if (addresses.size() > 0) {
                name = addresses.get(0).getLocality();
            } else {
                name = null;
            }
        } catch (Exception ignore) {
            name = null;
        }
        final String nameFinal = name;
        AndroidUtilities.runOnUIThread(() -> {
            Theme.autoNightCityName = nameFinal;
            if (Theme.autoNightCityName == null) {
                Theme.autoNightCityName = String.format("(%.06f, %.06f)", Theme.autoNightLocationLatitude,
                        Theme.autoNightLocationLongitude);
            }
            Theme.saveAutoNightThemeConfig();
            if (listView != null) {
                RecyclerListView.Holder holder = (RecyclerListView.Holder) listView
                        .findViewHolderForAdapterPosition(scheduleUpdateLocationRow);
                if (holder != null && holder.itemView instanceof TextSettingsCell) {
                    ((TextSettingsCell) holder.itemView).setTextAndValue(LocaleController
                            .getString("AutoNightUpdateLocation", R.string.AutoNightUpdateLocation),
                            Theme.autoNightCityName, false);
                }
            }
        });
    });
    RecyclerListView.Holder holder = (RecyclerListView.Holder) listView
            .findViewHolderForAdapterPosition(scheduleLocationInfoRow);
    if (holder != null && holder.itemView instanceof TextInfoPrivacyCell) {
        ((TextInfoPrivacyCell) holder.itemView).setText(getLocationSunString());
    }
    if (Theme.autoNightScheduleByLocation && Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SCHEDULED) {
        Theme.checkAutoNightThemeConditions();
    }
}

From source file:com.almalence.opencam.SavingService.java

protected void addTimestamp(File file, int exif_orientation) {
    try {//  w ww.j  av  a 2 s.  c o  m
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        int dateFormat = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampDate, "0"));
        boolean abbreviation = prefs.getBoolean(ApplicationScreen.sTimestampAbbreviation, false);
        int saveGeo = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampGeo, "0"));
        int timeFormat = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampTime, "0"));
        int separator = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampSeparator, "0"));
        String customText = prefs.getString(ApplicationScreen.sTimestampCustomText, "");
        int color = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampColor, "1"));
        int fontSizeC = Integer.parseInt(prefs.getString(ApplicationScreen.sTimestampFontSize, "80"));

        String formattedCurrentDate = "";
        if (dateFormat == 0 && timeFormat == 0 && customText.equals("") && saveGeo == 0)
            return;

        String geoText = "";
        // show geo data on time stamp
        if (saveGeo != 0) {
            Location l = MLocation.getLocation(getApplicationContext());

            if (l != null) {
                if (saveGeo == 2) {
                    Geocoder geocoder = new Geocoder(MainScreen.getMainContext(), Locale.getDefault());
                    List<Address> list = geocoder.getFromLocation(l.getLatitude(), l.getLongitude(), 1);
                    if (!list.isEmpty()) {
                        String country = list.get(0).getCountryName();
                        String locality = list.get(0).getLocality();
                        String adminArea = list.get(0).getSubAdminArea();// city
                        // localized
                        String street = list.get(0).getThoroughfare();// street
                        // localized
                        String address = list.get(0).getAddressLine(0);

                        // replace street and city with localized name
                        if (street != null)
                            address = street;
                        if (adminArea != null)
                            locality = adminArea;

                        geoText = (country != null ? country : "") + (locality != null ? (", " + locality) : "")
                                + (address != null ? (", \n" + address) : "");

                        if (geoText.equals(""))
                            geoText = "lat:" + l.getLatitude() + "\nlng:" + l.getLongitude();
                    }
                } else
                    geoText = "lat:" + l.getLatitude() + "\nlng:" + l.getLongitude();
            }
        }

        String dateFormatString = "";
        String timeFormatString = "";
        String separatorString = ".";
        String monthString = abbreviation ? "MMMM" : "MM";

        switch (separator) {
        case 0:
            separatorString = "/";
            break;
        case 1:
            separatorString = ".";
            break;
        case 2:
            separatorString = "-";
            break;
        case 3:
            separatorString = " ";
            break;
        default:
            separatorString = " ";
        }

        switch (dateFormat) {
        case 1:
            dateFormatString = "yyyy" + separatorString + monthString + separatorString + "dd";
            break;
        case 2:
            dateFormatString = "dd" + separatorString + monthString + separatorString + "yyyy";
            break;
        case 3:
            dateFormatString = monthString + separatorString + "dd" + separatorString + "yyyy";
            break;
        default:
        }

        switch (timeFormat) {
        case 1:
            timeFormatString = " hh:mm:ss a";
            break;
        case 2:
            timeFormatString = " HH:mm:ss";
            break;
        default:
        }

        Date currentDate = Calendar.getInstance().getTime();
        java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat(
                dateFormatString + timeFormatString);
        formattedCurrentDate = simpleDateFormat.format(currentDate);

        formattedCurrentDate += (customText.isEmpty() ? "" : ("\n" + customText))
                + (geoText.isEmpty() ? "" : ("\n" + geoText));

        if (formattedCurrentDate.equals(""))
            return;

        Bitmap sourceBitmap;
        Bitmap bitmap;

        int rotation = 0;
        Matrix matrix = new Matrix();
        if (exif_orientation == ExifInterface.ORIENTATION_ROTATE_90) {
            rotation = 90;
        } else if (exif_orientation == ExifInterface.ORIENTATION_ROTATE_180) {
            rotation = 180;
        } else if (exif_orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            rotation = 270;
        }
        matrix.postRotate(rotation);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inMutable = true;

        sourceBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        bitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(),
                matrix, false);

        sourceBitmap.recycle();

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        Paint p = new Paint();

        Canvas canvas = new Canvas(bitmap);

        final float scale = getResources().getDisplayMetrics().density;

        p.setColor(Color.WHITE);
        switch (color) {
        case 0:
            color = Color.BLACK;
            p.setColor(Color.BLACK);
            break;
        case 1:
            color = Color.WHITE;
            p.setColor(Color.WHITE);
            break;
        case 2:
            color = Color.YELLOW;
            p.setColor(Color.YELLOW);
            break;

        }

        if (width > height) {
            p.setTextSize(height / fontSizeC * scale + 0.5f); // convert dps
            // to pixels
        } else {
            p.setTextSize(width / fontSizeC * scale + 0.5f); // convert dps
            // to pixels
        }
        p.setTextAlign(Align.RIGHT);
        drawTextWithBackground(canvas, p, formattedCurrentDate, color, Color.BLACK, width, height);

        Matrix matrix2 = new Matrix();
        matrix2.postRotate(360 - rotation);
        sourceBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix2, false);

        bitmap.recycle();

        FileOutputStream outStream;
        outStream = new FileOutputStream(file);
        sourceBitmap.compress(Bitmap.CompressFormat.JPEG, jpegQuality, outStream);
        sourceBitmap.recycle();
        outStream.flush();
        outStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
    }
}

From source file:dynamite.zafroshops.app.MainActivity.java

public LocationBase getAddress(boolean force) {
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    SharedPreferences preferences = getPreferences(0);
    SharedPreferences.Editor editor = preferences.edit();
    boolean locationToggle = preferences.getBoolean(StorageKeys.LOCATION_TOGGLE_KEY, locationToggleDefault);

    try {// w ww. j  a  v  a2  s. c  om
        if (!force && LastLocation != null) {

            if (preferences.contains(StorageKeys.COUNTRY_KEY)
                    && !preferences.getString(StorageKeys.COUNTRY_KEY, "").equals("")) {
                LastLocation.CountryCode = preferences.getString(StorageKeys.COUNTRY_KEY, "");
                LastLocation.Town = preferences.getString(StorageKeys.TOWN_KEY, "");
                LastLocation.Street = preferences.getString(StorageKeys.STREET_KEY, "");
                LastLocation.StreetNumber = preferences.getString(StorageKeys.STREETNUMBER_KEY, "");
            }
        } else if (locationToggle && LastLocation != null) {
            List<Address> addresses = geocoder.getFromLocation(LastLocation.Latitude, LastLocation.Longitude,
                    1);

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

                LastLocation.CountryCode = address.getCountryCode();
                LastLocation.Town = address.getLocality();

                if (address.getMaxAddressLineIndex() > 0) {
                    String line = address.getAddressLine(0);

                    if (line.compareTo(LastLocation.Town) < 0) {
                        LastLocation.Street = line.replaceAll("(\\D+) \\d+.*", "$1");
                        LastLocation.StreetNumber = line.replaceAll("\\D+ (\\d+.*)", "$1");
                    }
                }

                editor.putString(StorageKeys.COUNTRY_KEY, LastLocation.CountryCode);
                editor.putString(StorageKeys.TOWN_KEY, LastLocation.Town);
                editor.putString(StorageKeys.STREET_KEY, LastLocation.Street);
                editor.putString(StorageKeys.STREETNUMBER_KEY, LastLocation.StreetNumber);
                editor.commit();
            }
        } else {
            return null;
        }

        return LastLocation;
    } catch (IOException e) {
        return null;
    }
}