Example usage for android.location Address getLocality

List of usage examples for android.location Address getLocality

Introduction

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

Prototype

public String getLocality() 

Source Link

Document

Returns the locality of the address, for example "Mountain View", or null if it is unknown.

Usage

From source file:org.metawatch.manager.Monitors.java

private static synchronized void updateWeatherDataGoogle(Context context) {
    try {// ww w.j  ava  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.laocuo.weather.presenter.impl.LocationPresenter.java

private String saveCityByLocation(Location l) {
    String city = null;/*from  w w w .j  a v a  2 s.  c  o m*/
    Double latitude = l.getLatitude();
    Double longitude = l.getLongitude();
    Geocoder gc = new Geocoder(mContext, Locale.getDefault());
    List<Address> addressList = null;
    try {
        addressList = gc.getFromLocation(latitude, longitude, 10);
        Address address = addressList.get(0);
        L.d("Locality:" + address.getLocality());
        city = address.getLocality();
        if (TextUtils.isEmpty(city) == false) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
            editor.putString(CITY_KEY, city);
            editor.commit();
        }
    } catch (IOException e) {
        e.printStackTrace();
        mView.getLocationFail();
    } finally {
        return city;
    }
}

From source file:semanticweb.hws14.movapp.activities.Criteria.java

private void useLocationData(Location location) {
    //Receive the location Data
    AlertDialog ad = new AlertDialog.Builder(that).create();
    ad.setCancelable(false); // This blocks the 'BACK' button
    Geocoder geocoder = new Geocoder(that, Locale.ENGLISH);
    try {//w ww . j a v a 2  s .c o  m
        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            final String strReturnedAdress = returnedAddress.getLocality();
            ad.setMessage("You are in: " + strReturnedAdress + "\nUse this location for the search?");

            ad.setButton(DialogInterface.BUTTON_POSITIVE, "YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    if (tabPosition == 0) {
                        MovieCriteria currentFragmet = (MovieCriteria) getFragmentByPosition(tabPosition);
                        currentFragmet.setGPSLocation(strReturnedAdress);
                    } else if (tabPosition == 1) {
                        ActorCriteria currentFragmet = (ActorCriteria) getFragmentByPosition(tabPosition);
                        currentFragmet.setGPSLocation(strReturnedAdress);
                    }

                    dialog.dismiss();
                }
            });

            ad.setButton(DialogInterface.BUTTON_NEGATIVE, "NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        } else {
            ad.setMessage("No Address returned!");
            ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
    } catch (IOException e) {
        e.printStackTrace();
        ad.setMessage("Can not get Address!");
        ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    ad.show();
    setProgressBarIndeterminateVisibility(false);
    locMgr.removeUpdates(locListner);
}

From source file:nl.hnogames.domoticz.UI.LocationDialog.java

private void setAddressData(Address foundLocation) {
    String address = foundLocation.getAddressLine(0) + ", " + foundLocation.getLocality();
    resolvedAddress.setText(address);/*from   ww w. j ava2s. c  om*/
    resolvedCountry.setText(foundLocation.getCountryName());
}

From source file:de.j4velin.wifiAutoOff.Locations.java

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (requestCode == REQUEST_LOCATION) {
        if (resultCode == RESULT_OK) {
            LatLng location = data.getParcelableExtra("location");
            String locationName = "UNKNOWN";
            if (Geocoder.isPresent()) {
                Geocoder gc = new Geocoder(this);
                try {
                    List<Address> result = gc.getFromLocation(location.latitude, location.longitude, 1);
                    if (result != null && !result.isEmpty()) {
                        Address address = result.get(0);
                        locationName = address.getAddressLine(0);
                        if (address.getLocality() != null) {
                            locationName += ", " + address.getLocality();
                        }/* w w  w.j av  a 2 s .  c om*/
                    }
                } catch (IOException e) {
                    if (BuildConfig.DEBUG)
                        Logger.log(e);
                    e.printStackTrace();
                }
            }
            Database db = Database.getInstance(this);
            db.addLocation(locationName, location);
            db.close();
            locations.add(new Location(locationName, location));
            mAdapter.notifyDataSetChanged();
        }
    } else if (requestCode == REQUEST_BUY) {
        if (resultCode == RESULT_OK) {
            if (data.getIntExtra("RESPONSE_CODE", 0) == 0) {
                try {
                    JSONObject jo = new JSONObject(data.getStringExtra("INAPP_PURCHASE_DATA"));
                    PREMIUM_ENABLED = jo.getString("productId").equals("de.j4velin.wifiautomatic.billing.pro")
                            && jo.getString("developerPayload").equals(getPackageName());
                    getSharedPreferences("settings", Context.MODE_PRIVATE).edit()
                            .putBoolean("pro", PREMIUM_ENABLED).commit();
                    if (PREMIUM_ENABLED) {
                        Toast.makeText(this, "Thank you!", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    if (BuildConfig.DEBUG)
                        Logger.log(e);
                    Toast.makeText(this, e.getClass().getName() + ": " + e.getMessage(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

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;//from w  w w.  j  a v a2  s .c o m
    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.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;// w  w  w.  j av  a2 s  . com
    }
    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:nl.hnogames.domoticz.Adapters.LocationAdapter.java

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
    int layoutResourceId;

    final LocationInfo mLocationInfo = data.get(position);
    holder = new ViewHolder();

    layoutResourceId = R.layout.geo_row_location;
    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    convertView = inflater.inflate(layoutResourceId, parent, false);

    if (mSharedPrefs.darkThemeEnabled()) {
        (convertView.findViewById(R.id.row_wrapper))
                .setBackground(ContextCompat.getDrawable(context, R.drawable.bordershadowdark));
        (convertView.findViewById(R.id.row_global_wrapper))
                .setBackgroundColor(ContextCompat.getColor(context, R.color.background_dark));

        if ((convertView.findViewById(R.id.remove_button)) != null)
            (convertView.findViewById(R.id.remove_button))
                    .setBackground(ContextCompat.getDrawable(context, R.drawable.button_status_dark));
    }//  w ww. ja v  a 2  s.  c om

    holder.enable = (CheckBox) convertView.findViewById(R.id.enableSwitch);
    holder.name = (TextView) convertView.findViewById(R.id.location_name);
    holder.radius = (TextView) convertView.findViewById(R.id.location_radius);
    holder.country = (TextView) convertView.findViewById(R.id.location_country);
    holder.address = (TextView) convertView.findViewById(R.id.location_address);
    holder.connectedSwitch = (TextView) convertView.findViewById(R.id.location_connectedSwitch);
    holder.remove = (Button) convertView.findViewById(R.id.remove_button);

    if (mLocationInfo.getAddress() != null) {
        Address address = mLocationInfo.getAddress();

        String addressString;
        String countryString;

        if (address != null) {
            addressString = address.getAddressLine(0) + ", " + address.getLocality();
            countryString = address.getCountryName();
        } else {
            addressString = context.getString(R.string.unknown);
            countryString = context.getString(R.string.unknown);
        }
        holder.address.setText(addressString);
        holder.country.setText(countryString);
    }

    holder.name.setText(mLocationInfo.getName());
    holder.radius.setText(context.getString(R.string.radius) + ": " + mLocationInfo.getRadius());

    if (!UsefulBits.isEmpty(mLocationInfo.getSwitchName())) {
        holder.connectedSwitch
                .setText(context.getString(R.string.connectedSwitch) + ": " + mLocationInfo.getSwitchName());
    } else if (mLocationInfo.getSwitchIdx() > 0) {
        holder.connectedSwitch
                .setText(context.getString(R.string.connectedSwitch) + ": " + mLocationInfo.getSwitchIdx());
    } else {
        holder.connectedSwitch.setText(
                context.getString(R.string.connectedSwitch) + ": " + context.getString(R.string.not_available));
    }

    if (!UsefulBits.isEmpty(mLocationInfo.getValue()))
        holder.connectedSwitch.setText(holder.connectedSwitch.getText() + " - " + mLocationInfo.getValue());

    holder.remove.setId(mLocationInfo.getID());
    holder.remove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            LocationInfo removeLocation = null;
            for (LocationInfo l : data) {
                if (l.getID() == v.getId()) {
                    removeLocation = l;
                }
            }
            if (removeLocation != null)
                handleRemoveButtonClick(removeLocation);
        }
    });

    holder.enable.setId(mLocationInfo.getID());
    holder.enable.setChecked(mLocationInfo.getEnabled());
    holder.enable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            for (LocationInfo locationInfo : data) {
                if (locationInfo.getID() == buttonView.getId()) {
                    if (!handleEnableChanged(locationInfo, holder.enable.isChecked())) {
                        buttonView.setChecked(false);
                    } else {
                        buttonView.setChecked(true);
                    }
                    break;
                }
            }
        }
    });

    convertView.setTag(holder);
    return convertView;
}

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 {/*  w  w  w .  jav a 2s. c  o  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.android.jhansi.designchallenge.MapFragment.java

private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
    try {//from   w ww . j a v a2  s  . c o m
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("");

            strReturnedAddress.append(returnedAddress.getAddressLine(0)).append(" ");
            strReturnedAddress.append(returnedAddress.getLocality());
            strAdd = strReturnedAddress.toString();
            Log.w(TAG, "" + strReturnedAddress.toString());
        } else {
            Log.w(TAG, "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w(TAG, "Canont get Address!");
    }
    return strAdd;
}