List of usage examples for android.location Address getCountryCode
public String getCountryCode()
From source file:com.googlecode.android_scripting.jsonrpc.JsonBuilder.java
private static JSONObject buildJsonAddress(Address address) throws JSONException { JSONObject result = new JSONObject(); result.put("admin_area", address.getAdminArea()); result.put("country_code", address.getCountryCode()); result.put("country_name", address.getCountryName()); result.put("feature_name", address.getFeatureName()); result.put("phone", address.getPhone()); result.put("locality", address.getLocality()); result.put("postal_code", address.getPostalCode()); result.put("sub_admin_area", address.getSubAdminArea()); result.put("thoroughfare", address.getThoroughfare()); result.put("url", address.getUrl()); return result; }
From source file:net.frakbot.FWeather.util.WeatherHelper.java
/** * Gets the city name (where available), suffixed with the * country code.//from w ww . jav a2 s.c o m * * @param context The current {@link Context}. * @param location The Location to get the name for. * * @return Returns the city name and country (eg. "London,UK") * if available, null otherwise */ public static String getCityName(Context context, Location location) { String cityName = null; if (Geocoder.isPresent()) { Geocoder geocoder = new Geocoder(context); List<Address> addresses = null; try { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); } catch (IOException ignored) { } if (addresses != null && !addresses.isEmpty()) { final Address address = addresses.get(0); final String city = address.getLocality(); if (!TextUtils.isEmpty(city)) { // We only set the city name if we actually have it // (to avoid the country code avoiding returning null) cityName = city + "," + address.getCountryCode(); } } } String encodedCityName = null; try { encodedCityName = URLEncoder.encode(cityName, "UTF-8"); } catch (UnsupportedEncodingException e) { FLog.d(context, TAG, "Could not encode city name, assume no city available."); } catch (NullPointerException enp) { FLog.d(context, TAG, "Could not encode city name, assume no city available."); } return encodedCityName; }
From source file:com.bottlerocketstudios.groundcontrolsample.product.controller.ProductController.java
public Region getBestRegion(Address address, RegionConfiguration regionConfiguration) { Region defaultRegion = null;//from w w w . j a va 2 s . c o m for (Region region : regionConfiguration.getRegionList()) { if (address.getCountryCode().equalsIgnoreCase(region.getRegion())) { return region; } if (RegionConfiguration.DEFAULT_REGION.equalsIgnoreCase(region.getRegion())) { defaultRegion = region; } } return defaultRegion; }
From source file:com.quantcast.measurement.service.QCLocation.java
private void sendLocation(Location location) { final Double lat = location.getLatitude(); final Double longTemp = location.getLongitude(); _geoTask = new AsyncTask<Double, Void, MeasurementLocation>() { @Override// w w w . j ava 2s.co m protected MeasurementLocation doInBackground(Double... params) { MeasurementLocation retval; double latitude = params[0]; double longitude = params[1]; QCLog.i(TAG, "Looking for address."); try { QCLog.i(TAG, "Geocoder."); List<Address> addresses = _geocoder.getFromLocation(latitude, longitude, 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); retval = new MeasurementLocation(address.getCountryCode(), address.getAdminArea(), address.getLocality(), address.getPostalCode()); } else { QCLog.i(TAG, "Geocoder reverse lookup failed."); retval = this.fallbackGeoLocate(latitude, longitude); } } catch (Exception e) { QCLog.i(TAG, "Geocoder API not available."); retval = this.fallbackGeoLocate(latitude, longitude); } return retval; } protected MeasurementLocation fallbackGeoLocate(double latitude, double longitude) { MeasurementLocation retval = null; // call googles map api directly MeasurementLocation geoInfo = lookup(latitude, longitude); if (geoInfo != null && !this.isCancelled()) { retval = geoInfo; } else { QCLog.i(TAG, "Google Maps API reverse lookup failed."); } return retval; } @Override protected void onPostExecute(MeasurementLocation address) { if (null != address && address.getCountry() != null) { QCLog.i(TAG, "Got address and sending..." + address.getCountry() + " " + address.getState() + " " + address.getLocality()); HashMap<String, String> params = new HashMap<String, String>(); params.put(QCEvent.QC_EVENT_KEY, QC_EVENT_LOCATION); if (address.getCountry() != null) { params.put(QC_COUNTRY_KEY, address.getCountry()); } if (address.getState() != null) { params.put(QC_STATE_KEY, address.getState()); } if (address.getLocality() != null) { params.put(QC_CITY_KEY, address.getLocality()); } if (address.getPostalCode() != null) { params.put(QC_POSTALCODE_KEY, address.getPostalCode()); } QCMeasurement.INSTANCE.logOptionalEvent(params, null, null); } } }; //Async execute needs to be on main thread if (Looper.getMainLooper().getThread() == Thread.currentThread()) { if (_geoTask != null && _geoTask.getStatus() == AsyncTask.Status.PENDING) { _geoTask.execute(lat, longTemp); } } else { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (_geoTask != null && _geoTask.getStatus() == AsyncTask.Status.PENDING) { _geoTask.execute(lat, longTemp); } } }); } }
From source file:com.google.android.apps.muzei.gallery.GalleryArtSource.java
private void ensureMetadataExists(@NonNull Uri imageUri) { Cursor existingMetadata = getContentResolver().query(GalleryContract.MetadataCache.CONTENT_URI, new String[] { BaseColumns._ID }, GalleryContract.MetadataCache.COLUMN_NAME_URI + "=?", new String[] { imageUri.toString() }, null); if (existingMetadata == null) { return;//from www .j av a2 s . co m } boolean metadataExists = existingMetadata.moveToFirst(); existingMetadata.close(); if (!metadataExists) { // No cached metadata or it's stale, need to pull it separately using Exif ContentValues values = new ContentValues(); values.put(GalleryContract.MetadataCache.COLUMN_NAME_URI, imageUri.toString()); InputStream in = null; try { ExifInterface exifInterface; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { in = getContentResolver().openInputStream(imageUri); exifInterface = new ExifInterface(in); } else { File imageFile = GalleryProvider.getLocalFileForUri(this, imageUri); if (imageFile == null) { return; } exifInterface = new ExifInterface(imageFile.getPath()); } String dateString = exifInterface.getAttribute(ExifInterface.TAG_DATETIME); if (!TextUtils.isEmpty(dateString)) { Date date = sExifDateFormat.parse(dateString); values.put(GalleryContract.MetadataCache.COLUMN_NAME_DATETIME, date.getTime()); } float[] latlong = new float[2]; if (exifInterface.getLatLong(latlong)) { // Reverse geocode List<Address> addresses = mGeocoder.getFromLocation(latlong[0], latlong[1], 1); if (addresses != null && addresses.size() > 0) { Address addr = addresses.get(0); String locality = addr.getLocality(); String adminArea = addr.getAdminArea(); String countryCode = addr.getCountryCode(); StringBuilder sb = new StringBuilder(); if (!TextUtils.isEmpty(locality)) { sb.append(locality); } if (!TextUtils.isEmpty(adminArea)) { if (sb.length() > 0) { sb.append(", "); } sb.append(adminArea); } if (!TextUtils.isEmpty(countryCode) && !sOmitCountryCodes.contains(countryCode)) { if (sb.length() > 0) { sb.append(", "); } sb.append(countryCode); } values.put(GalleryContract.MetadataCache.COLUMN_NAME_LOCATION, sb.toString()); } } getContentResolver().insert(GalleryContract.MetadataCache.CONTENT_URI, values); } catch (ParseException e) { Log.w(TAG, "Couldn't read image metadata.", e); } catch (IOException e) { Log.w(TAG, "Couldn't write temporary image file.", e); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } } }
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 {/*from w w w . j av a 2 s . c o m*/ 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; } }
From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service_test.java
private void getCurrentAddress(double longitude, double latitude) { Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); try {//w ww . j a v a 2 s. com List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1); if (addressList != null && addressList.size() > 0) { Address address = addressList.get(0); StringBuilder sb = new StringBuilder(); 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()); result.setLatitude(latitude); result.setLongitude(longitude); result.setCountryName(address.getCountryName()); result.setLocality(address.getLocality()); result.setZipCode(address.getPostalCode()); result.setLocation(sb.toString()); if (address.getCountryCode().equals("TW")) { result.setAddress(address.getAddressLine(0).substring(3, address.getAddressLine(0).length())); result.setLocation(address.getAddressLine(0).substring(3, address.getAddressLine(0).length())); } else { result.setAddress(sb.toString()); result.setLocation(sb.toString()); } curAddress = result.getAddress(); } } catch (IOException e) { Log.e("", "Unable connect to Geocoder", e); } //test = true; }
From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getCurrentGPSLocationBroadcastReceiver = new BroadcastReceiver() { @Override/*from w w w . j av a2 s . c om*/ public void onReceive(Context context, Intent intent) { // if(!test) { // textView.append("\n" +intent.getExtras().get("coordinates")); if (intent.getExtras().containsKey("longitude")) { double longitude = (double) intent.getExtras().get("longitude"); double latitude = (double) intent.getExtras().get("latitude"); googleMap.clear(); setMapView(longitude, latitude); Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); try { List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1); if (addressList != null && addressList.size() > 0) { Address address = addressList.get(0); StringBuilder sb = new StringBuilder(); 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()); result.setLatitude(latitude); result.setLongitude(longitude); result.setCountryName(address.getCountryName()); result.setLocality(address.getLocality()); result.setZipCode(address.getPostalCode()); result.setLocation(sb.toString()); if (address.getCountryCode().equals("TW")) { result.setAddress( address.getAddressLine(0).substring(3, address.getAddressLine(0).length())); result.setLocation( address.getAddressLine(0).substring(3, address.getAddressLine(0).length())); } else { result.setAddress(sb.toString()); result.setLocation(sb.toString()); } } } catch (IOException e) { Log.e("", "Unable connect to Geocoder", e); } //test = true; } // } } }; sendDataRequest = new JsonPutsUtil(getActivity()); sendDataRequest.setServerRequestOrderManagerCallBackFunction( new JsonPutsUtil.ServerRequestOrderManagerCallBackFunction() { @Override public void createNormalOrder(NormalOrder order) { if (progressDialog_loading != null) { progressDialog_loading.cancel(); progressDialog_loading = null; } Intent intent = new Intent(getActivity(), ClientTakeRideSearchActivity.class); Bundle b = new Bundle(); b.putInt(Constants.ARG_POSITION, Integer.valueOf(order.getTicket_id())); intent.putExtras(b); startActivity(intent); //finish(); } @Override public void cancelNormalOrder(NormalOrder order) { Intent intent = new Intent(getActivity(), MainActivity.class); startActivity(intent); //finish(); } }); }
From source file:com.astifter.circatext.YahooJSONParser.java
public Weather getWeather(String data, Address address) throws JSONException { Weather weather = new Weather(); // We create out JSONObject from the data JSONObject jObj = new JSONObject(data); JSONObject queryObj = getObject("query", jObj); try {//w w w. ja v a 2 s . c om @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); weather.time = sdf.parse(getString("created", queryObj)); } catch (Throwable t) { weather.time = null; } JSONObject resultsObj = getObject("results", queryObj); JSONObject channelObj = getObject("channel", resultsObj); JSONObject itemObj = getObject("item", channelObj); JSONObject condition = getObject("condition", itemObj); weather.currentCondition.setCondition(getString("text", condition)); int code = getInt("code", condition); weather.currentCondition.setWeatherId(code); weather.currentCondition.setDescr(Weather.translateYahoo(code)); float temperatureF = getFloat("temp", condition); float temperatureC = (temperatureF - 32f) / 1.8f; weather.temperature.setTemp(temperatureC); try { // Tue, 04 Aug 2015 10:59 pm CEST Locale l = Locale.ENGLISH; SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy hh:mm a", l); String date = getString("date", condition).replace("pm", "PM").replace("am", "AM"); weather.lastupdate = sdf.parse(date); } catch (Throwable t) { weather.lastupdate = null; } Location loc = new Location(); loc.setCountry(address.getCountryCode()); loc.setCity(address.getLocality()); weather.location = loc; return weather; }