android app implement google auto complete activity for 2 inputs - android

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.

Related

onActivityResult : android.net.Uri android.content.Intent.getData()' on a null object reference

Its work perfectly when i click image from the camera or back press from camera.
Ii also works perfectly when i select an image from the gallery but it occurs error when i back press from the gallery without selecting any image at this line filePath = data.getData();.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.net.Uri android.content.Intent.getData()' on a null
object reference
private void changeProfileImage() {
try {
PackageManager pm = getPackageManager();
int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
if (hasPerm == PackageManager.PERMISSION_GRANTED) {
final CharSequence[] options = {"Take Photo", "Choose From Gallery", "Cancel"};
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(AddProduct.this);
builder.setTitle("Select Option");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
dialog.dismiss();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, PICK_IMAGE_CAMERA);
} else if (options[item].equals("Choose From Gallery")) {
dialog.dismiss();
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
} else Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_CAMERA) {
try {
bitmap = (Bitmap) data.getExtras().get("data");
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_GALLERY) {
try {
filePath = data.getData();
if (filePath != null) {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Yes, If you not selected any Image and simply come back from the Gallery , It will return null in the Intent Data. Check data!=null before taking getData()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_CAMERA) {
try {
bitmap = (Bitmap) data.getExtras().get("data");
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_GALLERY) {
try {
if(data!=null)
{ // user selects some Image
filePath = data.getData();
if (filePath != null) {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
pro_img.setImageBitmap(bitmap);
img = getEncoded64ImageStringFromBitmap(bitmap);
}
}
else
{ // user simply backpressed from gallery
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

MediaPlayer doesn't work?

I want to play audio files with MediaPlayer. Audio files are not in resource.
What I want to do is like this.
get the file path.
register the file path to realm db.
fetch the file path from realm db.
set the file path to MediaPlayer (IOException happens here)
play
IOException happens When I call MediaPlayer#setDataSource(path).
I dont know where i am doing wrong
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_choose) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 999);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 999 && resultCode == RESULT_OK) {
final Uri uri = data.getData();
_realmObj.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
MyDb db = bgRealm.where(Song.class).equalTo("id", songIndex).findFirst();
db.setSongPath(uri.getDataString());
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
buttonPlay.setVisibility(View.VISIBLE);
}
});
}
super.onActivityResult(requestCode, resultCode, data);
}
private void PlaySong(int songIndex) {
MyDb db = _realmObj.where(Song.class).equalTo("id", songIndex).findFirst();
Uri path = db.getSongPath();
if (path == null) {
return;
}
try {
_mediaPlayer.setDataSource(URLDecoder.decode(path, "utf-8"));
_mediaPlayer.prepare();
_mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

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

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 place picker api, occur error in the searching process

Good Day,
I'm trying to use place picker api. From google.
public void onPickButtonClick(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intent, REQUEST_PLACE_PICKER);
} catch (GooglePlayServicesRepairableException e) {
// ...
} catch (GooglePlayServicesNotAvailableException e) {
// ...
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == REQUEST_PLACE_PICKER
&& resultCode == Activity.RESULT_OK) {
// The user has selected a place. Extract the name and address.
final Place place = PlacePicker.getPlace(data, this);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = PlacePicker.getAttributions(data);
if (attributions == null) {
attributions = "";
}
mViewName.setText(name);
mViewAddress.setText(address);
mViewAttributions.setText(Html.fromHtml(attributions));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
But it result in that after launching the application loading the places. It just flash and turn white and return to the page where i launch this application.
Thank You In Advance
code
public class POI extends ActionBarActivity {
int REQUEST_PLACE_PICKER = 1;
TextView mViewName, mViewAddress, mViewAttributions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poi_horizontal);
mViewName = (TextView) findViewById(R.id.name);
mViewAddress = (TextView) findViewById(R.id.address);
mViewAttributions = (TextView) findViewById(R.id.attributions);
}
public void PickButtonClick(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intent, REQUEST_PLACE_PICKER);
} catch (GooglePlayServicesRepairableException e) {
// ...
} catch (GooglePlayServicesNotAvailableException e) {
// ...
}
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == REQUEST_PLACE_PICKER
&& resultCode == POI.RESULT_OK) {
// The user has selected a place. Extract the name and address.
final Place place = PlacePicker.getPlace(data, this);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = PlacePicker.getAttributions(data);
if (attributions == null) {
attributions = "";
}
mViewName.setText(name);
mViewAddress.setText(address);
mViewAttributions.setText(Html.fromHtml(attributions));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_poi, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

Categories

Resources