Skip to content

Instantly share code, notes, and snippets.

@gavingt
Created June 8, 2019 10:03
Show Gist options
  • Save gavingt/ac5fecc305b0b9b0b53c7843a0c5ea3e to your computer and use it in GitHub Desktop.
Save gavingt/ac5fecc305b0b9b0b53c7843a0c5ea3e to your computer and use it in GitHub Desktop.
Geocoder Autocomplete
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new Filter.FilterResults();
if (constraint != null && constraint.length() > 1) {
String inputText = editText.getText().toString().toLowerCase().trim();
List<Address> tempAddressList = new ArrayList<>();
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocationName(inputText, 4, southwestLatLng.latitude,
southwestLatLng.longitude, northeastLatLng.latitude, northeastLatLng.longitude);
List<String> addressStringList = new ArrayList<>();
for (Address address : addresses) {
String currentAddressString = address.getAddressLine(0);
if (currentAddressString == null) {
continue;
}
currentAddressString = currentAddressString.split(",")[0].trim();
boolean matchVerified = matchFound(currentAddressString, inputText);
if (!addressStringList.contains(currentAddressString) && matchVerified) {
addressStringList.add(currentAddressString);
tempAddressList.add(address);
}
}
if (editText.getText().toString().isEmpty()) {
tempAddressList.clear();
}
} catch (IOException ioException) {
tempAddressList.clear();
networkErrorOccurred = true;
}
filterResults.values = tempAddressList;
filterResults.count = tempAddressList.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
addressList.clear();
notifyDataSetChanged();
if (results != null && results.count > 0) {
addressList.addAll((List<Address>) results.values);
notifyDataSetChanged();
networkErrorOccurred = false;
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment