Example usage for android.location Address getAddressLine

List of usage examples for android.location Address getAddressLine

Introduction

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

Prototype

public String getAddressLine(int index) 

Source Link

Document

Returns a line of the address numbered by the given index (starting at 0), or null if no such line is present.

Usage

From source file:com.vishwa.pinit.LocationSuggestionProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    switch (uriMatcher.match(uri)) {
    case SEARCH_SUGGEST:
        String query = uri.getLastPathSegment();

        MatrixCursor cursor = new MatrixCursor(SEARCH_SUGGEST_COLUMNS, 1);
        if (Geocoder.isPresent()) {
            try {
                mGeocoder = new Geocoder(getContext(), Locale.ENGLISH);
                List<Address> addressList = mGeocoder.getFromLocationName(query, 5);
                for (int i = 0; i < addressList.size(); i++) {
                    Address address = addressList.get(i);
                    StringBuilder fullAddress = new StringBuilder();
                    for (int j = 1; j < address.getMaxAddressLineIndex(); j++) {
                        fullAddress.append(address.getAddressLine(j));
                    }//from   ww w .ja v a  2 s . co  m
                    cursor.addRow(new String[] { Integer.toString(i), address.getAddressLine(0).toString(),
                            fullAddress.toString(), address.getLatitude() + "," + address.getLongitude() });
                }

                return cursor;
            } catch (IllegalArgumentException e) {
                return getLocationSuggestionsUsingAPI(query, cursor);
            } catch (IOException e) {
                return getLocationSuggestionsUsingAPI(query, cursor);
            }
        }
    default:
        throw new IllegalArgumentException("Unknown Uri: " + uri);
    }
}

From source file:eu.power_switch.gui.map.MapViewHandler.java

/**
 * Find a address description for a given coordinate
 *
 * @param latLng coordinate/* w w  w .  j  a  v a2  s .c  o  m*/
 * @return address description
 * @throws AddressNotFoundException
 */
public String findAddress(LatLng latLng) throws AddressNotFoundException {
    /* get latitude and longitude from the address */
    Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 5);
        if (addresses.size() > 0) {
            Address address = addresses.get(0);

            String addressAsString = address.getAddressLine(0);

            Log.d("Address; ", addressAsString);
            return addressAsString;
        } else {
            throw new AddressNotFoundException(
                    "latitude: " + latLng.latitude + ", longitude: " + latLng.longitude);
        }
    } catch (IOException e) {
        Log.e(e);
    }

    return null;
}

From source file:edu.usf.cutr.opentripplanner.android.tasks.OTPGeocoding.java

protected Long doInBackground(String... reqs) {
    long count = reqs.length;

    String address = reqs[0];//w  w w.j  a v a2s  . c  o m
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    if (address == null || address.equalsIgnoreCase("")) {
        return count;
    }

    if (address.equalsIgnoreCase(context.getString(R.string.my_location))) {
        String currentLat = reqs[1];
        String currentLng = reqs[2];
        LatLng latLng = new LatLng(Double.parseDouble(currentLat), Double.parseDouble(currentLng));

        Address addressReturn = new Address(context.getResources().getConfiguration().locale);
        addressReturn.setLatitude(latLng.latitude);
        addressReturn.setLongitude(latLng.longitude);
        addressReturn.setAddressLine(addressReturn.getMaxAddressLineIndex() + 1,
                context.getString(R.string.my_location));

        addressesReturn.add(addressReturn);

        return count;
    }

    ArrayList<Address> addresses = null;

    if (prefs.getBoolean(OTPApp.PREFERENCE_KEY_USE_ANDROID_GEOCODER, true)) {
        Log.d("test", "create a geocoder");
        Geocoder gc = new Geocoder(context);
        try {
            if (selectedServer != null) {
                addresses = (ArrayList<Address>) gc.getFromLocationName(address,
                        context.getResources().getInteger(R.integer.geocoder_max_results),
                        selectedServer.getLowerLeftLatitude(), selectedServer.getLowerLeftLongitude(),
                        selectedServer.getUpperRightLatitude(), selectedServer.getUpperRightLongitude());
            } else {
                addresses = (ArrayList<Address>) gc.getFromLocationName(address,
                        context.getResources().getInteger(R.integer.geocoder_max_results));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    addresses = filterAddressesBBox(addresses);

    if ((addresses == null) || addresses.isEmpty()) {
        addresses = searchPlaces(address);

        for (int i = 0; i < addresses.size(); i++) {
            Address addr = addresses.get(i);
            String str = addr.getAddressLine(0);
            List<String> addrLines = Arrays.asList(str.split(", "));
            for (int j = 0; j < addrLines.size(); j++) {
                addr.setAddressLine(j, addrLines.get(j));
            }
        }
    }

    addresses = filterAddressesBBox(addresses);

    addressesReturn.addAll(addresses);

    return count;
}

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));
    }//from  ww  w. jav 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.android.jhansi.designchallenge.MapFragment.java

private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
    try {//from ww w  .ja v a2s .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;
}

From source file:cmu.troy.applogger.AppService.java

private void logApps(List<String> newApps, List<String> currentApps) throws IOException {
    /*/* ww  w.  j  a  va 2s  .co m*/
     * Empty newApps means current apps are the same with the last apps. So there is no need to
     * update last apps file or log file.
     */
    if (newApps == null || newApps.size() == 0)
        return;

    lastApps = currentApps;
    Date now = new Date();

    /* Append new Apps into log file */
    JSONObject job = new JSONObject();
    String id = String.valueOf(now.getTime());
    try {
        job.put(JSONKeys.id, id);
        job.put(JSONKeys.first, newApps.get(0));
        job.put(JSONKeys.log_type, JSONValues.OPEN_AN_APP);
        /* Log Location block */
        Location mLocation = null;
        if (mLocationClient.isConnected())
            mLocation = mLocationClient.getLastLocation();
        if (mLocation != null) {
            job.put(JSONKeys.loc_available, true);
            job.put(JSONKeys.latitude, mLocation.getLatitude());
            job.put(JSONKeys.longitude, mLocation.getLongitude());
            job.put(JSONKeys.location_accuracy, mLocation.getAccuracy());
            job.put(JSONKeys.location_updated_time, (new Date(mLocation.getTime())).toString());

            Date updateTime = new Date(mLocation.getTime());
            if ((updateTime.getTime() - now.getTime()) / 60000 > 5) {
                Tools.runningLog("Last location is too old, a location update is triggered.");
                LocationRequest request = new LocationRequest();
                request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                mLocationClient.requestLocationUpdates(request, new LocationListener() {
                    @Override
                    public void onLocationChanged(Location arg0) {
                    }
                });
            }

            if (lastLocation == null || lastAddress == null
                    || lastLocation.distanceTo(mLocation) > Tools.SMALL_DISTANCE) {
                /* Log Address if location is available */
                Geocoder geocoder = new Geocoder(this, Locale.getDefault());
                List<Address> addresses = null;
                addresses = geocoder.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1);
                if (addresses != null && addresses.size() > 0) {
                    job.put(JSONKeys.addr_available, true);
                    Address address = addresses.get(0);
                    lastAddress = address;
                    job.put(JSONKeys.address,
                            address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "");
                    job.put(JSONKeys.city, address.getLocality());
                    job.put(JSONKeys.country, address.getCountryName());
                } else {
                    job.put(JSONKeys.addr_available, false);
                }
            } else {
                job.put(JSONKeys.addr_available, true);
                job.put(JSONKeys.address,
                        lastAddress.getMaxAddressLineIndex() > 0 ? lastAddress.getAddressLine(0) : "");
                job.put(JSONKeys.city, lastAddress.getLocality());
                job.put(JSONKeys.country, lastAddress.getCountryName());
            }
            lastLocation = mLocation;
        } else {
            if (!mLocationClient.isConnecting())
                mLocationClient.connect();
            job.put(JSONKeys.loc_available, false);
        }
    } catch (JSONException e) {
        Log.e("JSON", e.toString());
    }
    Tools.logJsonNewBlock(job);
}

From source file:com.mycompany.hw4.Maps.java

private void setUpMap() {
    Intent intent = getIntent();// w ww  .ja  v  a  2 s. co  m
    ArrayList<Parcelable> addresses = (ArrayList<Parcelable>) intent.getExtras()
            .getParcelableArrayList(MainActivity.LOCATION_MESSAGE);
    LatLng location = new LatLng(0, 0);
    PolylineOptions polyOpt = new PolylineOptions().geodesic(true).color(0xDDEE3333);

    for (Parcelable parcel : addresses) {
        Address address = (Address) parcel;
        location = new LatLng(address.getLatitude(), address.getLongitude());
        polyOpt.add(location);

        String marker;
        if (address.getFeatureName() != null) {
            marker = address.getFeatureName();
        } else if (address.getAddressLine(0) != null) {
            marker = address.getAddressLine(0);
        } else {
            marker = "Marker";
        }

        String snip = address.getLatitude() + " " + address.getLongitude() + "";

        map.addMarker(new MarkerOptions().position(location).title(marker).snippet(snip));
    }

    map.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(location, 14, 45, 0)));
    map.addPolyline(polyOpt);

    map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            map.animateCamera(
                    CameraUpdateFactory.newCameraPosition(new CameraPosition(marker.getPosition(), 14, 45, 0)));
            marker.showInfoWindow();
            return true;
        }
    });
}

From source file:org.jraf.android.piclabel.app.form.FormActivity.java

private String reverseGeocode(float lat, float lon) {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses;
    try {/* ww w . ja va  2 s.  c  o  m*/
        addresses = geocoder.getFromLocation(lat, lon, 1);
    } catch (Throwable t) {
        Log.w(TAG, "reverseGeocode Could not reverse geocode", t);
        return null;
    }
    if (addresses == null || addresses.isEmpty())
        return null;
    Address address = addresses.get(0);
    ArrayList<String> strings = new ArrayList<String>(5);
    if (address.getMaxAddressLineIndex() > 0)
        strings.add(address.getAddressLine(0));
    if (!TextUtils.isEmpty(address.getLocality()))
        strings.add(address.getLocality());
    if (!TextUtils.isEmpty(address.getCountryName()))
        strings.add(address.getCountryName());
    return TextUtils.join(", ", strings);
}

From source file:com.cianmcgovern.android.ShopAndShare.Share.java

/**
 * /*from   w w w . j  a  va 2  s  . c o m*/
 * Gets the address using the latitude and longitude from the getLocation()
 * 
 */
public void getAddress() {

    Geocoder geo = new Geocoder(this, Locale.ENGLISH);
    Address address = null;
    try {
        address = geo.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1).get(0);

        StringBuilder fullAddress = new StringBuilder();
        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
            fullAddress.append(address.getAddressLine(i) + " ");
        }
        Log.v(Constants.LOG_TAG, "Got address: " + fullAddress.toString());

        mLocationEdit.setText(fullAddress.toString().trim());
    } catch (IOException e) {
        e.printStackTrace();
    }
    mSearch.setBackgroundResource(R.drawable.search);
}

From source file:group5.trackerexpress.BasicMapActivity.java

protected void makeLatLngMarker(LatLng latLng, String locName, Integer zoom) {
    String snippet = "";

    if (locName == null) {
        locName = "";
    }//  w w  w  . j av a2s .com

    // https://developer.android.com/training/location/display-address.html 03/04/2015
    List<Address> addresses = null;

    try {
        addresses = mGeocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
    } catch (IOException ioException) {
        // Catch network or other I/O problems.
        System.err.println("Geocoder IO EXCEPTION");
    } catch (IllegalArgumentException illegalArgumentException) {
        // Catch invalid latitude or longitude values.
        System.err.println("Geocoder IllegalArgument at " + latLng.toString());
    }

    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        ArrayList<String> addressFragments = new ArrayList<String>();

        // Fetch the address lines using getAddressLine,
        // join them, and send them to the thread.
        if (address.getMaxAddressLineIndex() > 0) {
            if (locName.isEmpty()) {
                System.out.println("Location name is empty");
                locName = address.getAddressLine(0);
            }
            for (int i = 1; i <= address.getMaxAddressLineIndex(); i++) {
                addressFragments.add(address.getAddressLine(i));
            }
        }

        snippet = TextUtils.join(" ", addressFragments);
    }

    if (!snippet.isEmpty()) {
        snippet += System.getProperty("line.separator");
    }

    snippet += latLngFormat(latLng);

    makeMarker(latLng, locName, snippet);
    System.out.println("MAKING MARKER");
    goToMarker(lastMarker, zoom);
}