AutocompleteActivity Google Places API onActivityResult nothing happening - android

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

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()

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

How do I hide the speechRecogniser activity behind the main activity?

I am trying to hide the speech recogniser dialog that shows up saying "speak now" and written google as the title ,whenever i call it for passing some voice command. I don't want it to show up. Instead I want it to work in teh background so that the user cannot see it. What should be the correct way to do it?
public void getSpeechInput(View view) {
getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txvResult.setText(result.get(0));
String str = txvResult.getText().toString();
if(str.equals("lights on")){
Toast.makeText(MainActivity.this,
"matched", Toast.LENGTH_LONG).show();
count[0]=1;
turnOnFlash();
}
else if(str.equals("lights off")){
Toast.makeText(MainActivity.this,
"didnt", Toast.LENGTH_LONG).show();
count[0]=0;
turnOffFlash();
}
}
break;
}
}
I tried using this but it didn't work:-
getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
Try this. This listener catches the events and you can process them accordingly.
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(new RecognitionListener()
{
//Do whatever you want
});

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

print text from voice recognition in text view , except the first

I am using simple voice recognition .
I got it successfully working .
Lets say i spoke "Remark hey this is stack overflow"
I want to exclude "Remark" and print the rest of the text in a TextView.
Following is my work onActivityResult :-
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!textMatchList.isEmpty()) {
if(textMatchList.get(0).contains("Field"))
{
Intent non_field = new Intent(DashboardActivity.this,NonFieldActivity.class);
startActivity(non_field);
}
else if(textMatchList.get(0).contains("Tour"))
{
Intent non_field = new Intent(DashboardActivity.this,TourPlanActivity.class);
startActivity(non_field);
}
else {
final Dialog list_dialog;
ListView voice_match_list;
list_dialog = new Dialog(this);
list_dialog.setTitle("Matches");
list_dialog.setCancelable(true);
list_dialog.setContentView(R.layout.voice_list_dialog);
voice_match_list = (ListView) list_dialog.findViewById(R.id.voice_list);
voice_match_list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
Button cancel_button = (Button) list_dialog.findViewById(R.id.cancel_button_voice);
assert cancel_button != null;
cancel_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list_dialog.dismiss();
}
});
list_dialog.show();
}
}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Helper method to show the toast message
**/
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
My studies from google:-
.replace can be useful here, not able to understand how to use it with my code. Can some one suggest me article or help me with certain logic ?
you can do it by split method.
String message = "Remark hey this is stack overflow";
String [] arr = message.split(" ", 2);
Now arr[0] will contain "Remark" and arr[1] will contain "hey this is stack overflow"

Categories

Resources