Validate PlaceAutocompleteFragment in android - 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());
}
});

Related

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

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

Place Autocomplete how to do this right

I'm using following code
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
and
#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.
}
}
}
but dont see anythink what i want, so i wanna ask how to do some kind of listener on my EditText wich use PlaceAutocomplete to search for location, it should look like My EditText and under is my map, when I put K it will show all location starting at K under my EditText and I could choose it and marker location with camera smooth move
Well it could be done with
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.zzih(searchString)
.build(this);
Notice zzih method, it allows you to pass searchString to PlaceAutocomplete. Also in different versions of google services it can have another name.
The problem is that PlaceAutocomplete overlays entire screen so you cannot add your EditText over it.
When I faced same problem I had to implement UI by my self and use Google Places Web API because some features do not exists in Google Places Android API.
But you can try to use GeoDataApi.getAutocompletePredictions().
For using GeoDataApi.getAutocompletePredictions() you should:
Create field in your Fragment/Activity
private GoogleApiClient mGoogleApiClient;
Instantiate it and manage its lifecycle
#Override
protected void onCreate( Bundle savedInstanceState ) {
mGoogleApiClient = new GoogleApiClient
.Builder( this )
.enableAutoManage( this, 0, this )
.addApi( Places.GEO_DATA_API )
.addApi( Places.PLACE_DETECTION_API )
.addConnectionCallbacks( this )
.addOnConnectionFailedListener( this )
.build();
}
#Override
protected void onStart() {
super.onStart();
if( mGoogleApiClient != null )
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
if( mGoogleApiClient != null && mGoogleApiClient.isConnected() ) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
Create filter, list of available filters is here
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
.build();
Set bounds. Notice that first coordinate is southwest, seconds is northeast.
LatLngBounds bounds = new LatLngBounds(new LatLng(39.906374, -105.122337), new LatLng(39.949552, -105.068779));
Search for autocomplete prediction
Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, "my street",
SharedInstances.session().getCity().getBounds(), typeFilter).setResultCallback(new ResultCallback<AutocompletePredictionBuffer>() {
#Override
public void onResult(#NonNull AutocompletePredictionBuffer buffer) {
if( buffer == null )
return;
if( buffer.getStatus().isSuccess() ) {
for( AutocompletePrediction prediction : buffer ) {
Log.d(TAG,"Prediction placeId "+prediction.getPlaceId());
Log.d(TAG,"Prediction Primary Text "+prediction.getPrimaryText(null));
Log.d(TAG,"Prediction Secondary Text "+prediction.getSecondaryText(null));
}
//Prevent memory leak by releasing buffer
buffer.release();
}
});
Notice that AutocompletePrediction does not contain any information about coordinates. So if you need it you have to request Place object by placeId.
Places.GeoDataApi.getPlaceById( mGoogleApiClient, googlePlaceId).setResultCallback( new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if( places.getStatus().isSuccess() ) {
Place place = places.get( 0 );
}
//Release the PlaceBuffer to prevent a memory leak
places.release();
}});
I guess paragraphs 3. and 4. are not necessary so you can pass null instead.

Call Google Place Api on EditText

I am using google place API in my app and it's working perfectly when using fragment but, I want to call all the functionality on click on EditText. How to call that?
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
}
likelyPlaces.release();
}
});
If I am commenting this code from PlaceAutoCompleteFragment to before try block, yet it's working, so I don't understand from where it's is working and how to correct that:
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);
}
});
try {
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.build(this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
Here I am calling ActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
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.
}
}
}

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.
}
}
}

android app implement google auto complete activity for 2 inputs

I have 2 edit text inputs in my app.One is from place and another one to place.For these 2 inputs I have implemented google auto complete activity but problem when user click on any one of these inputs google autocomplete intent after user place selection completed intent call onActivityResult().
In onActivityResult() how to know which input clicked.
here is my code
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#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);
String fullName= (String) place.getAddress();
#// here I want to know which input clicked and set fullname in input text#
fromPlaceEdit.setText(fullName);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.i("fdfdf", status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
I did it different way.
I have created two global boolean value each for from place and to place.
then when user click on from place or to place change boolean value of same place then on onActivityResult check which boolean value is true and set result place name to same input box.
Code follows:
public boolean fromplaceSlected =false ;
public boolean toplaceSlected =false;
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("request", String.valueOf(requestCode));
// Check that the result was from the autocomplete widget.
if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == RESULT_OK) {
// Get the user's selected place from the Intent.
Place place = PlaceAutocomplete.getPlace(getContext(), data);
String fullName = (String) place.getAddress();
if(fromplaceSlected){
Log.e("from place",fullName);
fromPlaceEdit.setText(fullName);
fromplaceSlected=false;
toplaceSlected=false;
}
else if(toplaceSlected){
Log.e("toplace" ,fullName);
toPlaceEdit.setText(fullName);
fromplaceSlected=false;
toplaceSlected=false;
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getContext(), data);
Log.e("sdsdsdd", "Error: Status = " + status.toString());
fromplaceSlected=false;
toplaceSlected=false;
} else if (resultCode == RESULT_CANCELED) {
// Indicates that the activity closed before a selection was made. For example if
// the user pressed the back button.
fromplaceSlected=false;
toplaceSlected=false;
}
}
}
Your code may work, but it's a bit hacky. Here is the good way to do it:
public static final int PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE=1;
public static final int PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE=2;
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Do your stuff from place
startActivityForResult(intent, PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Do your stuff to place
startActivityForResult(intent, PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//Do your ok >from place< stuff here
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
//Handle your error >from place<
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
} else if (requestCode == PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//Do your ok >to place< stuff here
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
//Handle your error >to place<
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
From documentation:
requestCode int: If >= 0, this code will be returned in onActivityResult() when the activity exits.

Categories

Resources