How can i clear text of selected Place name from AutocompleteSupportFragment? - android

i create my project for ride booking app. I use AutocompleteSupportFragment for search place . After selecting Place , i filter that location if you are in Delhi then set Text of AutocompleteSupportFragment other wise set Hint like "Please select valid place".
I try
autocompleteFragment_to.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
if (!getStateName(place.getLatLng().latitude, place.getLatLng().longitude).equals("Madhya Pradesh")) {
Common.myLatLong = null;
Common.placeName1 = null;
Common.placeName1City = null;
Log.e("FRagmentData",""+autocompleteFragment_to.a.getText().toString());
autocompleteFragment_to.a.getText().toString();
autocompleteFragment_to.a.setText("");
autocompleteFragment_to.a.setHint("Please select Valid Place");
autocompleteFragment_to.getView().findViewById(R.id.places_autocomplete_clear_button).performClick();
autocompleteFragment_to.a.setText("");
Toast.makeText(context, "Please select Valid Place", Toast.LENGTH_SHORT).show();
} else {
destination = place.getLatLng();
Common.myLatLong = place.getLatLng();
Common.placeName1 = place.getName();
Log.e("FRagmentData",""+autocompleteFragment_to.a.getText().toString());
Common.placeName1City = getAddress(context, place.getLatLng().latitude, place.getLatLng().longitude);
if (mMap != null) {
mMap.clear();
}
mapFragment.getMapAsync(MainActivity.this);
}
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(context, "try again later", Toast.LENGTH_SHORT).show();
}
});
I try all these approch but it's not working

Use AutoComplete IntentBuilder instead of fragment..
Just initialise Places inside oncreate()
// Initialize Places.
Places.initialize(getApplicationContext(), "***YOUR API KEY***");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
then call intentbuilder in textview.onclick()
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields)
.build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
onActivity result you will get selected place.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
After that, just set the selected place in the Textview.
Textview.setText(place.getName());
refer:https://stackoverflow.com/a/55045772/10579969

Related

Google maps Autocomplete returns Place with null

I'm trying to get a Place from the Autocomplete of Google maps and then using its' longitude and latitude but every time I get a Place with the right name and all the other attributes got null in them. Does anyone know how to fix that?
Example of a Place I get:
I/System.out: Place{address=null, addressComponents=null, businessStatus=null, attributions=[], id=ChIJOwg_06VPwokRYv534QaPC8g, latLng=null, name=New York, openingHours=null, phoneNumber=null, photoMetadatas=null, plusCode=null, priceLevel=null, rating=null, types=null, userRatingsTotal=null, utcOffsetMinutes=null, viewport=null, websiteUri=null}
The code [the problem is at "setTargetPlace" (method is down the page)]:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place newTargetPlace = Autocomplete.getPlaceFromIntent(data);
System.out.println(newTargetPlace);
dataCenter.setTargetPlace(newTargetPlace);
dataCenter.createParty();
String response = dataCenter.getNextResponse();
System.out.println(response);
String[] commandAndPara = dataCenter.getCommandFromMsg(response);
String command = commandAndPara[0];
String para = commandAndPara[1];
if(command.equals(DataCenter.MSG_OK)) {
dataCenter.setPartyCode(para);
moveToParty();
}
else {
if(command.equals(DataCenter.MSG_FULL)) {
System.out.println("FULL");
}
else { //ERROR
System.out.println("ERROR");
}
}
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
The method:
public void setTargetPlace(Place targetPlace) {
this.targetPlace = targetPlace;
this.target = this.targetPlace.getName();
LatLng targetCords = this.targetPlace.getLatLng();
this.targetX = targetCords.longitude;
this.targetY = targetCords.latitude;
}
The reason why you are getting the latitude and longitude as null is because you didn't include LAT_LNG as part of the fields you want to retrieve. See the code snippet below to see how you can include it
val fields = listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG)
So when you create the intent and pass the field variable, and then go ahead to launch it like this
val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
.build(requireContext())
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE)
it will return with the latitude and longitude in onActivityResult()

AutocompleteActivity Google Places API onActivityResult nothing happening

I followed this guide on implementing placesautocomplete
https://developers.google.com/places/android-sdk/autocomplete
I followed the intent one not the fragment. Nothing happens when I select a place. It just shows me this picture when I click on a place :
enter image description here
I tried implementing the fragment version but same thing. Nothing happens.
#OnClick(R.id.editText) void searchLocation() {
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields).setTypeFilter(TypeFilter.ADDRESS).setCountry("PH").build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
displayLocationSettingsRequest(getApplicationContext());
break;
case AUTOCOMPLETE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
LatLng latLng = place.getLatLng();
String address = place.getAddress();
if (getIntent().getIntExtra("switch", 0) == 0) {
returnIntent.putExtra("pickup", address);
returnIntent.putExtra("latlng", latLng);
} else {
returnIntent.putExtra("dropoff", address);
returnIntent.putExtra("latlng", latLng);
}
selectedAddress = address;
editText.setText(address);
location.setText(address);
Toast.makeText(getApplicationContext(), address, Toast.LENGTH_SHORT).show();
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
Status status = Autocomplete.getStatusFromIntent(data);
Toast.makeText(getApplicationContext(), status.toString(), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
Toast.makeText(getApplicationContext(), "CANCELLED", Toast.LENGTH_SHORT).show();
}
}
}
I am forced to cancel the operation as selecting a place doesnt do anything and so resultcode always returns RESULT_CANCELLED

Validate PlaceAutocompleteFragment in android

I am trying to validate a PlaceAutocompleteFragment in android. I would like to add a toast if it is empty, if it is not empty then I want to do some processing. Here is my PlaceAutocompleteFragment. Is there an event listener I can attach to validate if no Place is selected?
FYI this is the Google Places API for Android
final PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("An error occured: " , status.toString());
}
});
You can also use place autocomplete request in place of using fragment like this
public void openPlaceAutoComplete() {
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.build(getActivity());
startActivityForResult(intent, Constants.PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
e.printStackTrace();
}
}
and you can get results like this on activity result method ...
if (resultCode == Activity.RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
setAddress(place.getAddress().toString(), place.getLatLng().latitude,
place.getLatLng().longitude);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getActivity(), "No places Selected", Toast.LENGTH_SHORT).show();
}
Create a latLng variable globally.
LatLng latLngPickup = null
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
//Place place = places.get(0);
latLngPickup = place.getLatLng();
}
Whenever you want to check if user has selected the place, check like this
if (latLngPickup == null) {
// your alert \\
return;
}
Sorry I had to add my code as an answer, I cant add a comment in reply to yours Rahul
Here is my code
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
LatLng latLngPickup = null;
#Override
public void onPlaceSelected(Place place) {
latLngPickup=place.getLatLng();
}
if(latLngPickup.latitude == null) {
Toast error = Toast.makeText(getApplicationContext(), "Please Select a location", Toast.LENGTH_LONG);
error.show();
return;
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("An error occured: " , status.toString());
}
});

Get country code from PlaceAutocomplete android (Google Places API)

We are using Google PlaceAutocomplete for city picker. We need to get country code for picked city. I am trying to use place.getLocale() but its null. Is there a way I can get Country ISO code from PlaceAutocomplete returned data.
in gradle:
compile 'com.google.android.gms:play-services-places:10.0.1'
code:
private void openCityPicker() {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
.build();
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.setFilter(typeFilter)
.build(this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
com.google.android.gms.location.places.Place googleApiPlace = PlaceAutocomplete.getPlace(this, data);
Log.d(TAG, "onActivityResult: " + googleApiPlace.getAddress());
Log.d(TAG, " googleApiPlace.getLocale().getCountry(): " + googleApiPlace.getLocale().getCountry());
Log.d(TAG, " googleApiPlace.getLocale().getDisplayCountry(): " + googleApiPlace.getLocale().getDisplayCountry());
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
late but right answer
you can get country code using this
add Place.Field.ADDRESS_COMPONENTS field into your fields list
List<Place.Field> fields = Arrays.asList(Place.Field.ADDRESS_COMPONENTS);
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields)
.setTypeFilter(TypeFilter.CITIES)
.build(mActivity);
startActivityForResult(intent, requestCode);
when you get the result into onActivityResult() you'll get full details of location into that you will find country
if (place.getAddressComponents() != null) {
List<AddressComponent> addressComponents = place.getAddressComponents().asList();
for (int i = 0; i < addressComponents.size(); i++) {
if (addressComponents.get(i).getTypes().get(0).equals("country")) {
countryCode = addressComponents.get(i).getShortName();
break;
}
}
}

Google's place autocomplete for android keeps giving me "Can't load search results"

I'm designing an app that uses maps and requires users to input destinations.i added the PlaceAutoCompleteFragment in the xml
fragment
android:id="#+id/place_autocomplete_fragment"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="top" android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
And this is what is in my java
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
When I try searching it says:"Can't load search results".What should I do after this?
The autocomplete widget is a search dialog with built-in autocomplete functionality.
Use PlaceAutocomplete.IntentBuilder to create an intent to launch the autocomplete widget as an intent. After setting the optional parameters, call build(Activity) and pass the intent to startActivityForResult(android.content.Intent, int).
int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
...
try {
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN).build(this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
To receive notification when a user has selected a place, your app should override the activity's onActivityResult(), checking for the request code you have passed for your intent, as shown in the following example.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
Log.i(TAG, "Place: " + place.getName());
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}

Categories

Resources