Java Code Examples for android.location.Address#getMaxAddressLineIndex()

The following examples show how to use android.location.Address#getMaxAddressLineIndex() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocationHelper.java    From Bus-Tracking-Parent with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
public static String getLocationName(Context context, double lat, double lon) {
    Geocoder g = new Geocoder(context);
    try {
        Address address = g.getFromLocation(lat, lon, 1).get(0);
        String address_line = "";
        int max_address = address.getMaxAddressLineIndex();
        for (int i = 0; i < max_address; i++) {

            address_line += address.getAddressLine(i) + " ";
        }
        return address_line;
    } catch (IOException | IndexOutOfBoundsException e) {
    }
    return null;
}
 
Example 2
Source File: SelectPositionActivity.java    From MuslimMateAndroid with GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("");

            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            strAdd = strReturnedAddress.toString();
            Log.w("My Current loction address", "" + strReturnedAddress.toString());
        } else {
            Log.w("My Current loction address", "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w("My Current loction address", "Canont get Address!");
    }
    return strAdd;
}
 
Example 3
Source File: SelectLocationTabsActivity.java    From MuslimMateAndroid with GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
        if (addresses != null) {
            Address returnedAddress = addresses.get(0);

            StringBuilder strReturnedAddress = new StringBuilder("");

            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            strAdd = strReturnedAddress.toString();
            Log.w("My Current loction address", "" + strReturnedAddress.toString());
        } else {
            Log.w("My Current loction address", "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w("My Current loction address", "Canont get Address!");
    }
    return strAdd;
}
 
Example 4
Source File: AddressLoc.java    From PocketMaps with MIT License 6 votes vote down vote up
/** Gets all lines from address.
 *  @return Array with a length of min 1. **/
public static ArrayList<String> getLines(Address address)
{
  ArrayList<String> list = new ArrayList<String>();
  putLine(list, address.getFeatureName());
  putLine(list, address.getThoroughfare());
  putLine(list, address.getUrl());
  putLine(list, address.getPostalCode());
  putLine(list, address.getSubThoroughfare());
  putLine(list, address.getPremises());
  putLine(list, address.getSubAdminArea());
  putLine(list, address.getAdminArea());
  putLine(list, address.getCountryCode());
  putLine(list, address.getCountryName());
  putLine(list, address.getSubLocality());
  putLine(list, address.getLocality());
  putLine(list, address.getPhone());
  for (int i=0; i<=address.getMaxAddressLineIndex(); i++)
  {
    putLine(list, address.getAddressLine(i));
  }
  if (list.size() == 0) { list.add(Variable.getVariable().getCountry()); }
  return list;
}
 
Example 5
Source File: GeocoderEx.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
private static List<AddressEx> getAddressList(List<Address> listAddress) {
    List<AddressEx> listAddressEx = new ArrayList<>();
    if (listAddress != null)
        for (Address address : listAddress)
            if (address.hasLatitude() && address.hasLongitude()) {
                List<String> listLine = new ArrayList<>();
                for (int l = 0; l < address.getMaxAddressLineIndex(); l++)
                    listLine.add(address.getAddressLine(l));
                AddressEx addressEx = new AddressEx();
                addressEx.name = TextUtils.join(", ", listLine);
                addressEx.location = new Location("geocoded");
                addressEx.location.setLatitude(address.getLatitude());
                addressEx.location.setLongitude(address.getLongitude());
                addressEx.location.setTime(System.currentTimeMillis());
                listAddressEx.add(addressEx);
            }
    return listAddressEx;
}
 
Example 6
Source File: SwipeableCardAdapter.java    From SwipeableCard with Apache License 2.0 6 votes vote down vote up
public String getStreetNameFromLatLong(double lat, double lon, Context context)
{
    String streetName = null;
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);

        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder();
            for (int j = 0; j < returnedAddress.getMaxAddressLineIndex(); j++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(j)).append("");
            }
            streetName = strReturnedAddress.toString();
        }
    } catch (IOException e) {
        Log.e("SwipeableCardAdapter", "Error tryng to retrieve street name from lat long");
    }
    return streetName;
}
 
Example 7
Source File: SwipeableCard.java    From SwipeableCard with Apache License 2.0 6 votes vote down vote up
/**
 * Get street name from latitude and longitude
 * @param lat latitude double
 * @param lon longitude double
 * @param context Context
 * @return String street name
 */
public String getStreetNameFromLatLong(double lat, double lon, Context context)
{
    String streetName = null;
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);

        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder();
            for (int j = 0; j < returnedAddress.getMaxAddressLineIndex(); j++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(j)).append("");
            }
            streetName = strReturnedAddress.toString();
        }
    } catch (IOException e) {
        Log.e("SwipeableCard", "Error tryng to retrieve street name from lat long");
    }
    return streetName;
}
 
Example 8
Source File: LocationReader.java    From MuslimMateAndroid with GNU General Public License v3.0 5 votes vote down vote up
public boolean locationToAddress(double latitude, double longitude) {

        Geocoder geocoder = new Geocoder(this.context, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses != null) {
                Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                locationInfo.clear();

                String city = returnedAddress.getAdminArea();
                if(city==null) city = returnedAddress.getLocality();

                locationInfo.put("country", returnedAddress.getCountryName());
                locationInfo.put("countrycode", returnedAddress.getCountryCode().toLowerCase());
                locationInfo.put("latitude", ""+returnedAddress.getLatitude());
                locationInfo.put("longitude", ""+returnedAddress.getLongitude());
                if(city!=null)locationInfo.put("city", ""+city);

                String address = "";
                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    address = address + returnedAddress.getAddressLine(i) + "\n";
                }
                locationInfo.put("address", address);

                return true;

            } else {
            }
        } catch (Exception e) {
        }

        return false;
    }
 
Example 9
Source File: AddressGeocoder.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
public static String addressToString(Address address) {
   	StringBuilder sb = new StringBuilder();
   	int max = address.getMaxAddressLineIndex();
   	for (int i = max; i >= 0; i--) {
   		String line = address.getAddressLine(i);
   		if (i < max) {
   			sb.append(", ");        			
   		}
   		sb.append(line);
   	}
   	return sb.toString();
}
 
Example 10
Source File: MainActivity.java    From RxGps with Apache License 2.0 5 votes vote down vote up
private String getAddressText(Address address) {
    String addressText = "";
    final int maxAddressLineIndex = address.getMaxAddressLineIndex();

    for (int i = 0; i <= maxAddressLineIndex; i++) {
        addressText += address.getAddressLine(i);
        if (i != maxAddressLineIndex) {
            addressText += "\n";
        }
    }

    return addressText;
}
 
Example 11
Source File: LocationSensor.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Physical street address of the device from Google's map database.
 *
 *   The address might not always be available from the provider, and the address reported may not
 * always be of the building where the device is located.
 *
 *   If Google has no address information available for a particular location, this will return
 * `No address available`.
 */
@SimpleProperty(category = PropertyCategory.BEHAVIOR,
    description = "Provides a textual representation of the current address or \"No address "
        + "available\".")
public String CurrentAddress() {
  if (hasLocationData &&
      latitude <= 90 && latitude >= -90 &&
      longitude <= 180 || longitude >= -180) {
    try {
      List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
      if (addresses != null && addresses.size() == 1) {
        Address address = addresses.get(0);
        if (address != null) {
          StringBuilder sb = new StringBuilder();
          for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
            sb.append(address.getAddressLine(i));
            sb.append("\n");
          }
          return sb.toString();
        }
      }

    } catch (Exception e) {
      // getFromLocation can throw an IOException or an IllegalArgumentException
      // a bad result can give an indexOutOfBoundsException
      // are there others?
      if (e instanceof IllegalArgumentException
          || e instanceof IOException
          || e instanceof IndexOutOfBoundsException ) {
        Log.e(LOG_TAG, "Exception thrown by getting current address " + e.getMessage());
      } else {
        // what other exceptions can happen here?
        Log.e(LOG_TAG,
            "Unexpected exception thrown by getting current address " + e.getMessage());
      }
    }
  }
  return "No address available";
}
 
Example 12
Source File: TrackNameUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the reverse geo coding string for a location.
 * 
 * @param context the context
 * @param location the location
 */
private static String getReverseGeoCoding(Context context, Location location) {
  if (location == null || !ApiAdapterFactory.getApiAdapter().isGeoCoderPresent()) {
    return null;
  }
  Geocoder geocoder = new Geocoder(context);
  try {
    List<Address> addresses = geocoder.getFromLocation(
        location.getLatitude(), location.getLongitude(), 1);
    if (addresses.size() > 0) {
      Address address = addresses.get(0);
      int lines = address.getMaxAddressLineIndex();
      if (lines > 0) {
        return address.getAddressLine(0);
      }
      String featureName = address.getFeatureName();
      if (featureName != null) {
        return featureName;
      }
      String thoroughfare = address.getThoroughfare();
      if (thoroughfare != null) {
        return thoroughfare;
      }
      String locality = address.getLocality();
      if (locality != null) {
        return locality;
      }
    }
  } catch (IOException e) {
    // Can safely ignore
  }
  return null;
}
 
Example 13
Source File: FetchAddressIntentService.java    From example with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    String error = "";

    // get location lat lng from activity
    Location location = intent.getParcelableExtra(MainActivity.TAG_LOCATION);
    receiver = intent.getParcelableExtra(MainActivity.TAG_RECEIVER);

    Geocoder geocoder = new Geocoder(this, Locale.getDefault());

    List<Address> listAddress = null;
    try {
        Log.d("debug", "get location... ");
        listAddress = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
    } catch (IOException e) {
        //error
    } catch (IllegalArgumentException ex) {
        // error
    }

    if (listAddress == null && listAddress.size() == 0) {
        // gagal mendapatkan alamat
        Log.d("debug", "gagal dapat alamat...");
        deliverResultToReceiver(MainActivity.RESULT_FAIL, "no adress fouund");
    } else {
        Log.d("debug", "berhasil dapat alamat...");
        // dapat alamat
        Address address = listAddress.get(0);
        ArrayList<String> addressFrag = new ArrayList<>();
        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
            addressFrag.add(address.getAddressLine(i));
        }

        // deliver
        deliverResultToReceiver(MainActivity.RESULT_SUCESS,
                TextUtils.join(System.getProperty("line.separator"),
                        addressFrag));
    }
}
 
Example 14
Source File: StartRide.java    From kute with Apache License 2.0 4 votes vote down vote up
public void reverseGeocodeSource(final Location location,final Integer index){
    Runnable r=new Runnable() {
        @Override
        public void run() {
            Log.i("ReverseGeocodeFirebase","Started runnable");
            String address="null";
            Geocoder geocoder= new Geocoder(getBaseContext(), Locale.ENGLISH);
            Double latitude=location.getLatitude();
            Double longitude=location.getLongitude();

            try {

                //Place your latitude and longitude
                List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1);

                if(addresses != null) {

                    Address fetchedAddress = addresses.get(0);
                    StringBuilder strAddress = new StringBuilder();


                    for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
                        strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
                    }
                    address=strAddress.toString();
                    source_address=address;
                    source_string=fetchedAddress.getAddressLine(1);
                    Log.d("ReverseGeocodeFirebase","The current Address is"+ address);
                    Log.d("ReverseGeocodeFirebase","The current source string  is"+ source_string);
                }

            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
            }
        }

    };
    reverse_geocode_handler.post(r);
}
 
Example 15
Source File: FetchAddressWorker.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public Result doWork() {
    try {
        //PPApplication.logE("FetchAddressWorker.doWork", "xxx");

        if (!PPApplication.getApplicationStarted(true))
            // application is not started
            return Result.success();

        Data outputData;

        // Get the input
        // Get the location passed to this service through an extra.
        double latitude = getInputData().getDouble(LocationGeofenceEditorActivity.LATITUDE_EXTRA, 0);
        double longitude = getInputData().getDouble(LocationGeofenceEditorActivity.LONGITUDE_EXTRA, 0);
        boolean updateName = getInputData().getBoolean(LocationGeofenceEditorActivity.UPDATE_NAME_EXTRA, false);

        Geocoder geocoder = new Geocoder(context, Locale.getDefault());

        List<Address> addresses = null;

        try {
            addresses = geocoder.getFromLocation(latitude, longitude,
                    // In this sample, get just a single address.
                    1);
        } catch (IOException ioException) {
            // Catch network or other I/O problems.
            //Log.e("FetchAddressWorker.doWork", "Service not available", ioException);
            //PPApplication.recordException(e);
        } catch (IllegalArgumentException illegalArgumentException) {
            // Catch invalid latitude or longitude values.
            /*Log.e("FetchAddressWorker.doWork", "Invalid location. " +
                    "Latitude = " + latitude +
                    ", Longitude = " +
                    longitude, illegalArgumentException);
            PPApplication.recordException(e);*/
        }

        // Handle case where no address was found.
        if (addresses == null || addresses.size() == 0) {
            //if (errorMessage.isEmpty()) {
            //Log.e("FetchAddressIntentService.onHandleIntent", "No address found");
            //}
            outputData = generateResult(LocationGeofenceEditorActivity.FAILURE_RESULT,
                    getApplicationContext().getString(R.string.event_preferences_location_no_address_found),
                    updateName);
        } else {
            Address address = addresses.get(0);
            ArrayList<String> addressFragments = new ArrayList<>();

            // Fetch the address lines using getAddressLine,
            // join them, and send them to the thread.
            for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                addressFragments.add(address.getAddressLine(i));
            }
            String lineSeparator = System.getProperty("line.separator");
            if (lineSeparator == null)
                lineSeparator = "\n";
            outputData = generateResult(LocationGeofenceEditorActivity.SUCCESS_RESULT,
                    TextUtils.join(lineSeparator, addressFragments),
                    updateName);
        }

        //if (outputData == null)
        //    return Result.success();
        //else
        // Return the output
        return Result.success(outputData);
    } catch (Exception e) {
        //Log.e("FetchAddressWorker.doWork", Log.getStackTraceString(e));
        PPApplication.recordException(e);
        return Result.failure();
    }
}
 
Example 16
Source File: FetchAddressIntentService.java    From location-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Tries to get the location address using a Geocoder. If successful, sends an address to a
 * result receiver. If unsuccessful, sends an error message instead.
 * Note: We define a {@link android.os.ResultReceiver} in * MainActivity to process content
 * sent from this service.
 *
 * This service calls this method from the default worker thread with the intent that started
 * the service. When this method returns, the service automatically stops.
 */
@Override
protected void onHandleIntent(Intent intent) {
    String errorMessage = "";

    mReceiver = intent.getParcelableExtra(Constants.RECEIVER);

    // Check if receiver was properly registered.
    if (mReceiver == null) {
        Log.wtf(TAG, "No receiver received. There is nowhere to send the results.");
        return;
    }

    // Get the location passed to this service through an extra.
    Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);

    // Make sure that the location data was really sent over through an extra. If it wasn't,
    // send an error error message and return.
    if (location == null) {
        errorMessage = getString(R.string.no_location_data_provided);
        Log.wtf(TAG, errorMessage);
        deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
        return;
    }

    // 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(this, Locale.getDefault());

    // Address found using the Geocoder.
    List<Address> addresses = null;

    try {
        // 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.
        addresses = geocoder.getFromLocation(
                location.getLatitude(),
                location.getLongitude(),
                // In this sample, we get just a single address.
                1);
    } catch (IOException ioException) {
        // Catch network or other I/O problems.
        errorMessage = getString(R.string.service_not_available);
        Log.e(TAG, errorMessage, ioException);
    } catch (IllegalArgumentException illegalArgumentException) {
        // Catch invalid latitude or longitude values.
        errorMessage = getString(R.string.invalid_lat_long_used);
        Log.e(TAG, errorMessage + ". " +
                "Latitude = " + location.getLatitude() +
                ", Longitude = " + location.getLongitude(), illegalArgumentException);
    }

    // Handle case where no address was found.
    if (addresses == null || addresses.size()  == 0) {
        if (errorMessage.isEmpty()) {
            errorMessage = getString(R.string.no_address_found);
            Log.e(TAG, errorMessage);
        }
        deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
    } else {
        Address address = addresses.get(0);
        ArrayList<String> addressFragments = new ArrayList<>();

        // Fetch the address lines using {@code getAddressLine},
        // join them, and send them to the thread. The {@link android.location.address}
        // class provides other options for fetching address details that you may prefer
        // to use. Here are some examples:
        // getLocality() ("Mountain View", for example)
        // getAdminArea() ("CA", for example)
        // getPostalCode() ("94043", for example)
        // getCountryCode() ("US", for example)
        // getCountryName() ("United States", for example)
        for(int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
            addressFragments.add(address.getAddressLine(i));
        }
        Log.i(TAG, getString(R.string.address_found));
        deliverResultToReceiver(Constants.SUCCESS_RESULT,
                TextUtils.join(System.getProperty("line.separator"), addressFragments));
    }
}