Example usage for android.location Address getPostalCode

List of usage examples for android.location Address getPostalCode

Introduction

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

Prototype

public String getPostalCode() 

Source Link

Document

Returns the postal code of the address, for example "94110", or null if it is unknown.

Usage

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:org.metawatch.manager.Monitors.java

private static synchronized void updateWeatherDataGoogle(Context context) {
    try {/*from w w  w .java  2 s.  c  o  m*/

        if (WeatherData.updating)
            return;

        // Prevent weather updating more frequently than every 5 mins
        if (WeatherData.timeStamp != 0 && WeatherData.received) {
            long currentTime = System.currentTimeMillis();
            long diff = currentTime - WeatherData.timeStamp;

            if (diff < 5 * 60 * 1000) {
                if (Preferences.logging)
                    Log.d(MetaWatch.TAG, "Skipping weather update - updated less than 5m ago");

                //IdleScreenWidgetRenderer.sendIdleScreenWidgetUpdate(context);

                return;
            }
        }

        WeatherData.updating = true;

        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherDataGoogle(): start");

        String queryString;
        List<Address> addresses;
        if (Preferences.weatherGeolocation && LocationData.received) {
            Geocoder geocoder;
            String locality = "";
            String PostalCode = "";
            try {
                geocoder = new Geocoder(context, Locale.getDefault());
                addresses = geocoder.getFromLocation(LocationData.latitude, LocationData.longitude, 1);

                for (Address address : addresses) {
                    if (!address.getPostalCode().equalsIgnoreCase("")) {
                        PostalCode = address.getPostalCode();
                        locality = address.getLocality();
                        if (locality.equals("")) {
                            locality = PostalCode;
                        } else {
                            PostalCode = locality + ", " + PostalCode;
                        }

                    }
                }
            } catch (IOException e) {
                if (Preferences.logging)
                    Log.e(MetaWatch.TAG, "Exception while retreiving postalcode", e);
            }

            if (PostalCode.equals("")) {
                PostalCode = Preferences.weatherCity;
            }
            if (locality.equals("")) {
                WeatherData.locationName = PostalCode;
            } else {
                WeatherData.locationName = locality;
            }

            queryString = "http://www.google.com/ig/api?weather=" + PostalCode;
        } else {
            queryString = "http://www.google.com/ig/api?weather=" + Preferences.weatherCity;
            WeatherData.locationName = Preferences.weatherCity;
        }

        URL url = new URL(queryString.replace(" ", "%20"));

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);
        xr.parse(new InputSource(url.openStream()));
        WeatherSet ws = gwh.getWeatherSet();
        WeatherCurrentCondition wcc = ws.getWeatherCurrentCondition();

        ArrayList<WeatherForecastCondition> conditions = ws.getWeatherForecastConditions();

        int days = conditions.size();
        WeatherData.forecast = new Forecast[days];

        for (int i = 0; i < days; ++i) {
            WeatherForecastCondition wfc = conditions.get(i);

            WeatherData.forecast[i] = m.new Forecast();
            WeatherData.forecast[i].day = null;

            WeatherData.forecast[i].icon = getIconGoogleWeather(wfc.getCondition());
            WeatherData.forecast[i].day = wfc.getDayofWeek();

            if (Preferences.weatherCelsius) {
                WeatherData.forecast[i].tempHigh = wfc.getTempMaxCelsius().toString();
                WeatherData.forecast[i].tempLow = wfc.getTempMinCelsius().toString();
            } else {
                WeatherData.forecast[i].tempHigh = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMaxCelsius()));
                WeatherData.forecast[i].tempLow = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMinCelsius()));
            }
        }

        WeatherData.celsius = Preferences.weatherCelsius;

        String cond = wcc.getCondition();
        WeatherData.condition = cond;

        if (Preferences.weatherCelsius) {
            WeatherData.temp = Integer.toString(wcc.getTempCelcius());
        } else {
            WeatherData.temp = Integer.toString(wcc.getTempFahrenheit());
        }

        cond = cond.toLowerCase();

        WeatherData.icon = getIconGoogleWeather(cond);
        WeatherData.received = true;
        WeatherData.timeStamp = System.currentTimeMillis();

        Idle.updateIdle(context, true);
        MetaWatchService.notifyClients();

    } catch (Exception e) {
        if (Preferences.logging)
            Log.e(MetaWatch.TAG, "Exception while retreiving weather", e);
    } finally {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherData(): finish");
    }

}

From source file:com.cloudbees.gasp.activity.GaspLocationsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_locations);

    GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    LocationManager locationManager;// w  ww.j  a  va2 s. c om
    String svcName = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(svcName);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);
    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);
    Log.i(TAG, "CURRENT LOCATION");
    Log.i(TAG, "Latitude = " + location.getLatitude());
    Log.i(TAG, "Longitude = " + location.getLongitude());

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

        if (!Geocoder.isPresent())
            Log.i(TAG, "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(" ");

                    sb.append(address.getLocality()).append("");
                    sb.append(address.getPostalCode()).append(" ");
                    sb.append(address.getCountryName());
                }
                Log.i(TAG, "Address: " + sb.toString());
            } catch (IOException e) {
                Log.d(TAG, "IOException getting address from geocoder", e);
            }
        }
    }

    map.setMyLocationEnabled(true);

    LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
    CameraPosition cameraPosition = new CameraPosition.Builder().target(myLocation).zoom(16).bearing(0).tilt(0)
            .build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    new LocationMapper().execute();
}

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  . jav a 2 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.jbsoft.farmtotable.FarmToTableActivity.java

private void getZipFromLocation(final Location location, final Context context) {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    try {//from  w  w w .  j  av  a2 s.c o m
        List<Address> list = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (list != null && list.size() > 0) {
            Address address = list.get(0);
            // sending back first address line and locality
            zipcode = address.getPostalCode();
        }
    } catch (IOException e) {
        Log.e(TAG, "Impossible to connect to Geocoder", e);
    } finally {
    }
}

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 {/*from   w w w .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 ww. ja  v  a2 s.co  m
        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.cecs492a_group4.sp.SingleEvent.java

public String reverseGeocode(double latitude, double longitude) throws IOException {
    Geocoder gc = new Geocoder(this);

    if (gc.isPresent()) {
        List<Address> list = gc.getFromLocation(latitude, longitude, 1);

        //(latitude, longitude, 1)
        //33.777043, -118.114395, 1)

        Address address = list.get(0);

        StringBuffer str = new StringBuffer();

        if (address.getAddressLine(0) != null && address.getLocality() != null && address.getAdminArea() != null
                && address.getPostalCode() != null && address.getCountryName() != null) {
            //str.append(address.getAddressLine(0) + ", ");
            //str.append(address.getLocality() + ", ");
            //str.append(address.getAdminArea() + " ");
            //str.append(address.getPostalCode() + ", ");
            //str.append(address.getCountryName());
            //str.append("USA");

            //String strAddress = str.toString();

            String strAddress = (address.getAddressLine(0) + ", " + address.getLocality() + ", "
                    + address.getAdminArea() + " " + address.getPostalCode() + ", " + "USA");

            return strAddress;
        } else {/*from w  w  w  . jav  a 2 s .co  m*/
            return null;
        }
    }

    return null;
}