I'm using an autocomplete_fragment to allow my users to search for places. After clicking the fragment it opens up the search menu, and you can type and the suggestions will appear. However, after clicking on any place the "onPlaceSelected" method won't run. After that clicking on the fragment won't make it respond either.
This fragment is in an activity with a map. I tried using the same fragment (same code and same layout) on another activity which only had text and it worked as expected. What could be happening in this activity that is making this behavior occur?
Here's the code showing the onCreate method, which calls some other methods which I wouldn't expect to be the source of the problem.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Initialize Places.
Places.initialize(getApplicationContext(), "myapikey");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
// Initialize the AutocompleteSupportFragment.
autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// Specify the types of place data to return.
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
// Set up a PlaceSelectionListener to handle the response.
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i("CHECK4", "Place: " + place.getName() + ", " + place.getId());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("CHECK4", "An error occurred: " + status);
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapView = mapFragment.getView();
mapFragment.getMapAsync(this);
anchorView = findViewById(R.id.anchorView);
buttonRoutes = findViewById(R.id.buttonRoutes);
buttonMenu = findViewById(R.id.buttonMenu);
buttonRoutes.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent routesIntent = new Intent(MapsActivity.this, RoutesActivity.class);
startActivity(routesIntent);
}
});
buttonMenu.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent routesIntent = new Intent(MapsActivity.this, MenuActivity.class);
startActivity(routesIntent);
}
});
routeIds = getIdsList();
routeTitles = getTitlesList();
routeCamera = getCameraList();
routeZoom = getZoomList();
initializeAllRoutes();
initializeAllStops();
RRdistance = new HashMap<Pair<Integer, Integer>, Double>();
initializeRRdistance();
geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
checkFirstTime();
}
For some reason, something in this particular activity is breaking the autocompletefragment. No errors are shown, just nothing happens.
Edit: I tried removing different parts of my activity until the autocomplete fragment worked, and I managed to find what was going on that way. The OnActivityResult method for some reason is the cause of the problem. Deleting the method made the autocomplete fragment work.
The OnActivityResult method for some reason is the cause of the problem. Deleting the method made the autocomplete fragment work. I was using this method before migrating to the new places API.
Trying to get autocomplete fragment to work in my code. TAG causes an error in the code, if you remove the Log statement it causes an error for the whole paragraph. it also does not let me TAG create a variable for tag to remove the error, if i do this the whole paragraph gets an error as well.
Have gone through the deprecation steps and added the new dependencies and imports and it still wont work...
also Places API is definitely already enabled
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
Meanwhile the Places SDK for Android provides this API:
dependencies {
implementation "com.google.android.gms:play-services-places:16.0.0"
implementation "com.google.android.libraries.places:places:1.0.0"
}
The AutocompleteSupportFragment in this package is not deprecated, but the whole package you are using. See the migration guide, in case you may already have some code which runs against that deprecated package.
And if TAG is unknown, you probably should define it; for example:
private static final String TAG = "PlacesActivity";
Google has recently updated their Places SDK for android, so now I'm updating my code too. I'm trying to use the AutocompleteSupportFragment to allow the user to set their address.
This is my code:
mAddressEditText = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.address);
mAddressEditText.setPlaceFields(Arrays.asList(Place.Field.ADDRESS, Place.Field.LAT_LNG));
mAddressEditText.setHint("Address");
mAddressEditText.setText("Test1"); // Works fine at the beginning, disappears after selecting a place and shows only the hint
mAddressEditText.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d(TAG, "Place Selected");
// Other Stuff
mAddressEditText.setText("Test2"); // Doesn't Work, all I can see is the hint
mAddressEditText.setText(place.getAddress()); // Doesn't Work, all I can see is the hint
}
#Override
public void onError(Status status) {
Log.e(TAG, "An error occurred: " + status);
invalidAddressDialog.show();
}
});
In the previous SDK, the fragment would set the text to the selected address automatically. This doesn't work in the new SDK (not sure if that's intentional or not).
So I'm trying to set it manually instead. As you can see in the comments in my code, using setText works fine outside the listeners. Inside the listener they don't.
Am I doing something wrong or is this a bug?
EDIT:
So long and I still can't get a proper fix to this.
To be perfectly clear, I can get the address correctly from the fragment, the only thing that doesn't work is setText.
However, since some answers state they're not getting the same problem, I started thinking it might be related to the library versions I'm using?
These are the libraries I have in my build.gradle:
api 'com.android.support:appcompat-v7:28.0.0'
api 'com.android.support:support-annotations:28.0.0'
api 'com.android.support:multidex:1.0.3'
api 'com.google.firebase:firebase-core:16.0.8'
api 'com.google.firebase:firebase-auth:16.2.1'
api 'com.google.firebase:firebase-firestore:18.2.0'
api 'com.google.firebase:firebase-storage:16.1.0'
api 'com.google.android.libraries.places:places:1.1.0'
setText has been giving me the same problem - it must be a bug I think. However I found a little work around with the hint. In your onPlaceSelected you can put the following:
Java
EditText etPlace = (EditText) autocompleteFragment.getView().findViewById(R.id.places_autocomplete_search_input);
etPlace.setHint(place.getAddress())
Kotlin
val etPlace = autocompleteFragment.view?.findViewById(R.id.places_autocomplete_search_input) as EditText
etPlace.hint = place.address
This is the code that I am using and it is working perfectly fine.
Make some changes to build.gradle (app level)
Add this to build.gradle:
android{
...
ext {
googlePlayServicesVersion = "15.0.1"
}
}
Add those dependencies:
dependencies {
...
//Also if you're using any firebase dependencies make sure that the are up to date
implementation 'com.google.android.gms:play-services-places:16.0.0'
implementation 'com.google.android.libraries.places:places:1.1.0'
}
apply plugin: 'com.google.gms.google-services'
In xml layout:
<fragment
android:id="#+id/autocomplete_fragment"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
The code in Activity:
private void initGooglePlacesApi() {
// Initialize Places.
Places.initialize(getApplicationContext(), "YOUR_API_KEY");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(getApplicationContext());
// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setHint(getString(R.string.select_location_search_bar));
// autocompleteFragment.setLocationRestriction(RectangularBounds.newInstance(
// new LatLng(34.7006096, 19.2477876),
// new LatLng(41.7488862, 29.7296986))); //Greece bounds
autocompleteFragment.setCountry("gr");
// Specify the types of place data to return.
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ADDRESS, Place.Field.ADDRESS_COMPONENTS));
autocompleteFragment.setTypeFilter(TypeFilter.ADDRESS);
// Set up a PlaceSelectionListener to handle the response.
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
if(place.getAddressComponents().asList().get(0).getTypes().get(0).equalsIgnoreCase("route")){
binding.textViewLocation.setText(place.getAddress()); //Works well
location = place.getAddress();
}else{ //If user does not choose a specific place.
AndroidUtils.vibratePhone(getApplication(), 200);
TastyToast.makeText(getApplicationContext(),
getString(R.string.choose_an_address), TastyToast.DEFAULT, TastyToast.CONFUSING);
}
Log.i(TAG, "Place: " + place.getAddressComponents().asList().get(0).getTypes().get(0) + ", " + place.getId() + ", " + place.getAddress());
}
#Override
public void onError(Status status) {
Log.i(TAG, "An error occurred: " + status);
}
});
}
I found a pretty simple solution..just delay a little bit the moment you set the text in the EditText. So in your PlaceSelectionListener just do it this way:
Handler().postDelayed({
mAddressEditText.setText(place.getAddress());
}, 300)
PS: This is kotlin code but It's almost similar in Java
By setting "NAME" in setPlaceFields, a selected address is automatically shown in the fragment:
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// Set "Place.Field.NAME" as below here to show the selected item //
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, **Place.Field.NAME**,Place.Field.ADDRESS,Place.Field.LAT_LNG));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
// TODO: Get info about the selected place. }
#Override
public void onError(#NonNull Status status) {
// TODO: Handle the error. }
});
I believe this is a bug, because it doesn't make sense to have it working like this.
What does work is set other autocomplete's texts but not its own.
This has to be a bug.
EDIT: here is my updated answer
# When you are using AutocompleteSupportFragment or AutocompleteActivity
# in Fragments, do this:
public class YourFragment extends Fragment {
/.../
#Override
public void onActivityResult (int requestCode,int resultCode,
#Nullable Intent data){
# AUTOCOMPLETE_REQUEST_CODE is just a unique constant, define it
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == AutocompleteActivity.RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
// when resultcode is RESULT_OK
mAddressEditText.setText(place.getName());
// Notice this line, update your editText up here
}else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
Status status = Autocomplete.getStatusFromIntent(data);
// Handle error
} else if (resultCode == AutocompleteActivity.RESULT_CANCELED) {
// Handle results if canceled
}
super.onActivityResult(requestCode, resultCode, data);
}
}
/.../
}
# If you are extending AppCompatActivity, you might want to do this
# ONLY when you are already doing something in onActivityResult
public class YourActivity extends AppCompatActivity{
/.../
#Override
public void onActivityResult (int requestCode,int resultCode,#Nullable Intent data){
# your logic here.
/.../
# if you are already overriding onActivityResult,
# do not forget to put this line
super.onActivityResult(requestCode, resultCode, data);
}
/.../
}
I was having the problem too. Turns out you HAVE to override this and implement it anyway, whether using AutocompleteSupportFragment or AutocompleteActivity if you are working in Fragments.
If you are using AppCompatActivity you do not have to implement it, but if you are already overiding onActivityResult to do something, do not forget to call the base method super.onActivityResult
get the reference of AutoCompleteFragment and then set text to the autocomplete fragment
like
autoCompleteFragment.setText("Address")
for reference you can have a look at the documentation
https://developers.google.com/android/reference/com/google/android/gms/location/places/ui/PlaceAutocompleteFragment
I tried CacheMeOutside's solution but it didn't work at all. So, I decided to try Matthias's solution and it did work because the text actually sets and then immediately removes for some reason. A small delay fixes it. The delay can be as small as 1 millisecond.
If my solution doesn't work for you, you can try to experiment with the delay. It also seems that it doesn't stop view rendering, so you can set any time you want.
private lateinit var autocomplete: AutocompleteSupportFragment
override fun onPlaceSelected(place: Place) {
Timer("SetAddress", false).schedule(1) {
autocomplete.setText(place.address)
}
}
The code snippet in Kotlin. If your code is in Java, just find some instrument to delay code execution for some time.
The solution by Matthias is working but it is in kotlin. Below is the same implementation in Java
#Override
public void onPlaceSelected(Place place) {
String name = place.getName()+", "+place.getAddress();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
autocompleteFragmentDestination.setText(name);
}
},300);
}
Simple. Use a Spannable string to set the color!
val autocompleteFragment = childFragmentManager.findFragmentById(R.id.location_filter_autocomplete) as AutocompleteSupportFragment
val text = SpannableString("Enter a location")
text.setSpan(ForegroundColorSpan(Color.BLACK), 0, text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
autocompleteFragment.setHint(text)
Do the same inside onPlaceSelectedListener()
I am using the Google Snapshot API in Android.
I use this code to get the user's activity and store it to Firebase.
//Get user's current activity
private void myCurrentActivity(final String timestamp) {
if (checkPermission()) {
Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient)
.setResultCallback(new ResultCallback<DetectedActivityResult>() {
#Override
public void onResult(#NonNull DetectedActivityResult detectedActivityResult) {
if (detectedActivityResult.getStatus().isSuccess()) {
Log.d(TAG, "myCurrentActivity - SUCCESS");
ActivityRecognitionResult activityRecognitionResult = detectedActivityResult.getActivityRecognitionResult();
databaseReference.child(getUID(getApplicationContext(), "myCurrentActivity")).child(timestamp).child("activity").setValue(getActivityString(activityRecognitionResult.getMostProbableActivity().getType()));
Log.d(TAG, "Most Propable Activity : " + getActivityString(activityRecognitionResult.getMostProbableActivity().getType()));
} else {
Log.d(TAG, "myCurrentActivity - FAILURE");
databaseReference.child(getUID(getApplicationContext(), "myCurrentActivity")).child(timestamp).child("activity").setValue("null");
}
}
});
}
}
The problem is that the onResult function is never executed when i run it.
Do you have any ideas what may cause this ?
Thank you.
EDIT: I just ran it in the emulator and it's working without problems. Is it possible that this has something to do with my device ?
I am building an android app that saves a place ID retrieved from the PlaceAutocomplete API. At a later point, I am trying to get the details of the place using the getPlaceById() API. I see that the callback is never getting called.
I have set the following permission:
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
I have also added the API_KEY:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value=<API KEY>/>
However, I am unable to retrieve the place details. "onResult" never seems to be getting called. Can anyone please help me with where I might be going wrong?
Thanks!
Below is the code snippet that I am using. Have hardcoded the PlaceId here for simplicity :
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mGoogleApiClient, "ChIJi-t8KwUWrjsRlp-L9ykb2_k");
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
Log.i(TAG, "Testing");
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
Log.i(TAG, "Place found: " + myPlace.getName());
} else {
Log.e(TAG, "Place not found");
}
places.release();
}
});
I just found out what I was missing out. I missed out the call to mGoogleApiClient.connect(); in the onStart() of the activity. Works like a charm now! :)
The comment in the onCreate() in the below link states that we need to call connect() and disconnect() explicitly if the activity does not extend FragmentActivity.
https://github.com/tangqi92/MyGooglePlaces/blob/master/app/src/main/java/itangqi/me/mygoogleplaces/MainActivity.java
I got the same problem. And actually it's not "not getting invoked" but "haven't run yet".
Here is my wrong code.
public void onClick(View v) {
hideSoftKeyboard();
Log.i("Search Click", "getting Place: " + mMyLocation.id);
if(mMyLocation.id != null) {
Places.GeoDataApi.getPlaceById(mGoogleApiClient, mMyLocation.id)
.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if (places.getStatus().isSuccess() && places.getCount() > 0) {
LatLng coord = places.get(0).getLatLng();
mMyLocation.setLatLng(coord.latitude, coord.longitude);
Log.i("Place by id", "Place found: " + mMyLocation.coordinateString);
} else {
Log.e("Place by id", "Place not found");
}
places.release();
}
});
searchNearby();
}
}
The searchNearby()function uses mMyLocation that should have been changed in onResult. And it hasn't been changed yet, which means onResult hasn't been called before the searchNearby() run.
Then I put the function searchNearby() into onResult and it worked.
So my suggestion would be: put anything you want to run after onResult into it.