Skip to content

Instantly share code, notes, and snippets.

@chandruark
Last active June 4, 2019 12:03
Show Gist options
  • Save chandruark/aa558c65091596ef1a1bf43992e9b788 to your computer and use it in GitHub Desktop.
Save chandruark/aa558c65091596ef1a1bf43992e9b788 to your computer and use it in GitHub Desktop.
Google Place API Adapter - New Version Based on A new version of the Places SDK for Android -on ( 3-JUN-2019)
/**
* Place this Snippet in Activity File
* Secure `YOUR_GOOGLE_PLACE_API_KEY` Key in Build Config, if you need
*/
/**
* `etGoogleplaceApi` stands for AutocompleteEditText Widget
* Add Your Billings Details in Google Console, OR else it throws `QUERY_LIMIT_EXCEEDED` exception
* checkout for API KEY creation -> https://developers.google.com/places/android-sdk/get-api-key
* Remove Old dependency & Add Dependency in build.gradle (Module:app) level
* => implementation 'com.google.android.libraries.places:places:1.1.0'
*/
GooglePlaceAdapter mPlaceArrayAdapter = new GooglePlaceAdapter(this, android.R.layout.simple_spinner_dropdown_item,BOUNDS_MOUNTAIN_VIEW, "YOUR_GOOGLE_PLACE_API_KEY");
etGoogleplaceApi.setThreshold(3);
etGoogleplaceApi.setAdapter(mPlaceArrayAdapter);
package <your package>;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
/**
* Edited - New version of Places API
*
* Chandru
* 4/Jun/2018
*
* Google Place API Adapter Based on New Dependency Updation ,
* Advantage - which Removes *Powered By Google Logo
*/
public class GooglePlaceAdapter extends ArrayAdapter<PlaceArrayAdapter.PlaceAutocomplete> implements Filterable {
private static final String TAG = "PlaceArrayAdapter";
private PlacesClient placesClient;
private RectangularBounds mBounds;
private ArrayList<PlaceAutocomplete> mResultList = new ArrayList<>();
public Context context;
/**
* Constructor
* @param context Context
* @param resource Layout resource
* @param bounds Used to specify the search bounds
*/
public GooglePlaceAdapter(Context context, int resource, RectangularBounds bounds,String api_key) {
super(context, resource);
this.context = context;
mBounds = bounds;
Places.initialize(context, api_key);
placesClient = Places.createClient(context);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
return view;
}
@Override
public int getCount() {
if (mResultList == null)
return 0;
else
return mResultList.size();
}
@Override
public PlaceAutocomplete getItem(int position) {
return mResultList.get(position);
}
/**
* prediction.getFullText = Shows Entire Address Name
* prediction.getPrimaryText = Shows City Name
* prediction.getSecondaryText = Shows Street Address
*
*
* @param constraint
* @return
*/
private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) {
final ArrayList<PlaceAutocomplete> resultList = new ArrayList<>();
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call either setLocationBias() OR setLocationRestriction().
.setLocationBias(mBounds)
.setCountry("in")
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(constraint.toString())
.build();
Task<FindAutocompletePredictionsResponse> autocompletePredictions = placesClient.findAutocompletePredictions(request);
// This method should have been called off the main UI thread. Block and wait for at most
// 60s for a result from the API.
try {
Tasks.await(autocompletePredictions, 60, TimeUnit.SECONDS);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
e.printStackTrace();
}
if (autocompletePredictions.isSuccessful()) {
FindAutocompletePredictionsResponse findAutocompletePredictionsResponse = autocompletePredictions.getResult();
if (findAutocompletePredictionsResponse != null)
for (com.google.android.libraries.places.api.model.AutocompletePrediction prediction : findAutocompletePredictionsResponse.getAutocompletePredictions()) {
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getFullText(null).toString() ));
}
return resultList;
} else {
return resultList;
}
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null) {
// Query the autocomplete API for the entered constraint
mResultList = getPredictions(constraint);
if (mResultList != null) {
// Results
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
notifyDataSetInvalidated();
}
}
};
return filter;
}
/**
* Object for Population of Address
*/
public class PlaceAutocomplete {
public CharSequence placeId;
public CharSequence description;
PlaceAutocomplete(CharSequence placeId, CharSequence description) {
this.placeId = placeId;
this.description = description;
}
@Override
public String toString() {
return description.toString();
}
}
}
@chandruark
Copy link
Author

The End Result Would Be:

Which is Handy and Customized
Without Powered By Google Option at END.

photo_2019-06-04_13-01-18

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment