Example usage for android.location Address getAdminArea

List of usage examples for android.location Address getAdminArea

Introduction

In this page you can find the example usage for android.location Address getAdminArea.

Prototype

public String getAdminArea() 

Source Link

Document

Returns the administrative area name of the address, for example, "CA", or null if it is unknown

Usage

From source file:grandroid.geo.Geocoder.java

public static String convertAddress(double lat, double lng) throws Exception {
    List<Address> adds = getFromLocation(lat, lng, 1);
    if (adds == null || adds.isEmpty()) {
        throw new Exception("no address can be found");
    } else {//w  w w . jav  a 2s . c o m
        Address add = adds.get(0);
        if (add.getFeatureName() == null) {
            return add.getAdminArea() + add.getLocality() + add.getAddressLine(0);
        } else {
            return add.getFeatureName();
        }
    }
}

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:grandroid.geo.Geocoder.java

public static String convertAddress(double lat, double lng, boolean nation, boolean city, boolean district,
        boolean street) throws Exception {
    List<Address> adds = getFromLocation(lat, lng, 1);
    if (adds == null || adds.isEmpty()) {
        throw new Exception("no address can be found");
    } else {//from   w  w  w . ja va2 s .  c o m
        Address add = adds.get(0);
        StringBuilder sb = new StringBuilder();
        if (nation) {
            sb.append(add.getCountryName());
        }
        if (city) {
            sb.append(add.getAdminArea());
        }
        if (district) {
            sb.append(add.getLocality());
        }
        if (street) {
            sb.append(add.getAddressLine(0));
        }
        return sb.toString();
    }
}

From source file:ca.itquality.patrol.util.weather.YahooWeather.java

public static String addressToPlaceName(final Address address) {
    String result = "";
    if (address.getLocality() != null) {
        result += address.getLocality();
        result += " ";
    }//  ww w  .j av a2s  .  c  o m
    if (address.getAdminArea() != null) {
        result += address.getAdminArea();
        result += " ";
    }
    if (address.getCountryName() != null) {
        result += address.getCountryName();
        result += " ";
    }
    return result;
}

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  w  w  w  .ja v a 2  s .  c o  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:com.example.tj.weather.WeatherActivity.java

private void wearSearchRequest(Intent intent) {
    Log.i("onNewIntent()", "called");

    String location = intent.getStringExtra("message");

    if (location != null) {
        Geocoder geocoder = new Geocoder(this);

        List<Address> addressList = null;

        try {//  ww w. j  ava  2s. co m
            addressList = geocoder.getFromLocationName(location, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (addressList != null) {
            Address address = addressList.get(0);

            if (address != null) {
                onCityChanged(address.getLocality().toLowerCase(), address.getAdminArea().toLowerCase());
            }
        }
    }
}

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/*from   w w  w.  j  a  va2 s .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.berniesanders.fieldthebern.controllers.LocationController.java

private Address getAddressForLocation(double lat, double lng) throws AddressUnavailableException {
    // Errors could still arise from using the Geocoder (for example, if there is no
    // connectivity, or if the Geocoder is given illegal location data). Or, the Geocoder may
    // simply not have an address for a location. In all these cases, we communicate with the
    // receiver using a resultCode indicating failure. If an address is found, we use a
    // resultCode indicating success.

    // The Geocoder used in this sample. The Geocoder's responses are localized for the given
    // Locale, which represents a specific geographical or linguistic region. Locales are used
    // to alter the presentation of information such as numbers or dates to suit the conventions
    // in the region they describe.
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    List<Address> addresses = null;
    Address address = null;
    try {//  www .jav  a 2  s .c  om
        // Using getFromLocation() returns an array of Addresses for the area immediately
        // surrounding the given latitude and longitude. The results are a best guess and are
        // not guaranteed to be accurate.
        // In this sample, we get just a single address.
        addresses = geocoder.getFromLocation(lat, lng, 1);
    } catch (IOException | IllegalArgumentException ioException) {
        throw new AddressUnavailableException();
    }

    // Handle case where no address was found.
    if (addresses == null || addresses.size() == 0) {
        throw new AddressUnavailableException();
    } else {
        address = addresses.get(0);

        if (address == null || StringUtils.isBlank(address.getAdminArea())) {
            throw new AddressUnavailableException("address or state code was null/blank");
        }

        return address;
    }
}

From source file:com.yayandroid.utility.MapHelperFragment.java

/**
 * Parses found address object from GeoCoder, and posts informations
 *///from w  w  w  .  j a v a2s  .co  m
private void parseAddressInformation(Address address) {

    /**
     * This parsing also may need to be modified up to your country's
     * addressing system
     */

    String value = address.getSubLocality();
    if (value != null)
        PostInformation(LocInfoType.COUNTY, value);

    value = address.getLocality();
    if (value != null)
        PostInformation(LocInfoType.LOCALITY, value);

    value = address.getAdminArea();
    if (value != null)
        PostInformation(LocInfoType.CITY, value);

    value = address.getCountryName();
    if (value != null)
        PostInformation(LocInfoType.COUNTRY, value);

    // If there is still some fields to get information about, then post
    // googleMap api to get them
    boolean isThereAnyLeft = false;
    for (int i = 0; i < requiredInformations.length; i++) {
        if (!requiredInformations[i].hasSent) {
            isThereAnyLeft = true;
        }
    }

    if (isThereAnyLeft)
        fetchInformationUsingGoogleMap();

}

From source file:com.RSMSA.policeApp.OffenceReportForm.java

public String getAddress(double lat, double lng) {
    Geocoder geocoder = new Geocoder(OffenceReportForm.this, Locale.getDefault());
    String address = "";
    try {/* w  w w  .ja  v  a 2 s  .c om*/
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        Address obj = addresses.get(0);
        String add = "";
        if (obj.getAdminArea() != null) {
            add = add + obj.getAdminArea();
        }
        if (obj.getSubAdminArea() != null) {
            add = add + ", " + obj.getSubAdminArea();
        }
        if (obj.getAddressLine(0) != null) {
            add = add + ", " + obj.getAddressLine(0);
        }
        address = add;

        Log.v("IGA", "Address" + add);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {

    }
    return address;
}