Google places getPlaceById callback not getting invoked - android

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.

Related

AlertDialog showing unexpectedly

in my app I have a permissions method that checks and asks for permissions if build codes are >= 23, I have implemented AlertDialog to achieve this and show rationale if needed. The problem is when I test on lollipop a dialog window with the app's name pops up every time the app is started, I have fully protected all methods involved to not do anything if build codes are less than 23, so how and why is this dialog box still showing? Here's an image of the rouge dialog box:
And here is all the related code:
public void GMASInit() {
linkGms = RunnerActivity.CurrentActivity;
linkGms.startActivity(new Intent(linkGms, AudioSave.class));
}
protected void onStart() {//RunnerJNILib.ms_context
super.onStart();
if (Build.VERSION.SDK_INT >= 23) {
getPerms();
}
//other unrelated code.....
}
public void getPerms() {
if (Build.VERSION.SDK_INT >= 23) {
try { // Determine weather developer included optional WRITE_SETTINGS permission in the manifest
PackageInfo info = getPackageManager().getPackageInfo(linkGms.getPackageName(), PackageManager.GET_PERMISSIONS);
if (info.requestedPermissions != null) {
for (String p : info.requestedPermissions) {
if (p.contains("WRITE_SETTINGS")) {
perms = 3;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
final List<String> permissionsList = new ArrayList<String>();
if(!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO)) {permissionsNeeded.add("Record Audio");}
if(!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {permissionsNeeded.add("Write storage");}
Log.i("yoyo","Number of permissions in manifest: " + String.valueOf(perms));
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
if (perms == 2) {
message = message + " " + msg1 + " and " + msg2 + " " + "to save and load data and record audio.";
}
if (perms == 3) {
message = message + " " + msg1 + ", " + msg2 + " and " + msg3 + " " + "to save and load data, record audio and change ringtone.";
}
Log.i("yoyo","Message to be shown: " + message);
showMessageOKCancel(message, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
if (Build.VERSION.SDK_INT >= 23) {
if (!Settings.System.canWrite(linkGms) && perms == 3) {
Intent writeset = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
writeset.setData(Uri.parse("package:" + linkGms.getPackageName()));
linkGms.startActivity(writeset);
}
linkGms.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), Get_Permission);
finish();
}
}
});
return;
}
}
finish();
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= 23) {
if (linkGms.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
if (!linkGms.shouldShowRequestPermissionRationale(permission))
return false;
}
}
return true;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
if (Build.VERSION.SDK_INT >= 23) {
new AlertDialog.Builder(linkGms).setTitle(msg0).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", null).create().show();
}
}
As you can see I've gone overkill in trying to prevent this problem, Also note that it's only this dialog box showing (the one in the picture), the permissions dialog box does not show (which is expected). Also more info that might be helpfull/related is when testing android os 23 and up the dialog box I showed you shows above the permissions dialog box, and you have to click outside of it to dismiss it so the actual permissions dialog box can be accessed. please tell me where I've gone wrong and how to fix it, thanks.
I figured it out, it was a strange situation indeed, it had nothing to do with the permissions or alert dialog builder at all, if fact I discovered it by removing all those methods and the alert dialog imports and it still happened, so instead the problem was related to my manifest activity level style code statement. I have this activity statement in my manifest:
<activity android:name=".AudioSave"
android:theme="#android:style/Theme.Holo.Dialog" >
</activity>
So this was causing a conflict with how I have to call the onStart method, but I need the theme for my app, so all I had to do to fix it was to add finish(); before the last closing curly bracket at the end of my onStart method. problem solved, like this:
protected void onStart() {
super.onStart();
//bla bla bla...
finish();
}

Snapshot API - ResultCallBack not triggered

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 ?

RouteListener returning ROUTING_CANCELLED in some calculations (Here-api)

Well, my RouteListener sometimes return ROUTING_CANCELLED. I look in documentation and it's says: "An application user cancelled the calculation."
RouteListener
private class RouteListener implements RouteManager.Listener {
// Method defined in Listener
public void onProgress(int percentage) {
// Display a message indicating calculation progress
}
// Method defined in Listener
public void onCalculateRouteFinished(RouteManager.Error error, List<RouteResult> routeResult) {
if (error == RouteManager.Error.NONE) {
// Logic here
} else {
Toast.makeText(context, "Calc error: " + error.name(), Toast.LENGTH_LONG).show();
}
}
}
How to avoid this error? I'm lost x_x ~. Are something in my phone irregular?
Obs: Internet, GPS, battery and cpu are fine.
Aggregating answer from the comments.
Reverse Geocoding in here maps only work after MapEngine initialization. Calling the Reverse Geocoding before the MapEngine initialization will trigger a ROUTE_CANCELLED error.

Multiple PlaceAutoCompleteFragment opens when clicked on it very quickly

I am using Google's PlaceAutoCompleteFragment in a recent project that I am currently working on. When I click on the PlaceAutoCompleteFragment very quickly it open multiple overlays on my app which is really annoying. how can I prevent it from opening multiple overlays? My code for the fragment is given below:
if (autocompleteFragment == null) {
autocompleteFragment = (PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.place_autocompletehome_fragment);
}
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
try {
Log.i("esty", "Place: " + place.getName());
} catch (Exception e) {
Log.e("esty", "Error: " + e.getMessage());
}
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.e("esty", "An error occurred: " + status);
}
});
It looks like this is a bug in PlaceAutocompleteFragment (and SupportPlaceAutocompleteFragment). Thank you for bringing it to our attention. We'll look at fixing this in an upcoming release.
Why don't you try a hack to solve this problem.
Put a on click listener on the whole fragment and use multi click blocker to pass the click event once.
Refer to the below solution :
https://stackoverflow.com/a/23103227/4901098

How to generate referral code using Branch.io Metrics?

I am trying to implement a referral code system, and I am using Branch.io Metrics library. The problem I am facing is that the documentation is not good (doesn't work) and I am unable to generate a code
Documentation:
https://github.com/BranchMetrics/Branch-Android-SDK#register-an-activity-for-direct-deep-linking-optional-but-recommended
Here are the steps I have taken including adding the library.
1) Grabbed the jar, added to my libs folder and added the following to my depenencies
compile files('libs/branch-1.5.9.jar')
2) In my application class that extends Application I added the following
if (DEBUG) {
Branch.getAutoTestInstance(this);
} else {
Branch.getAutoInstance(this);
}
3) In my AndroidManifest.xml I added the following
<meta-data android:name="io.branch.sdk.BranchKey" android:value="#string/bnc_app_key" />
4) In the Activity that I am testing everything, I added in the onStart() method the following
#Override
protected void onStart() {
// note that branch is a global variable (Branch branch;)
if (DEBUG) {
branch = Branch.getTestInstance(this.getApplicationContext());
} else {
branch = Branch.getInstance(this.getApplicationContext());
}
branch.initSession(new BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject jsonObject, BranchError branchError) {
if (branchError == null) {}
}, this.getIntent().getData(), this;
}
From the above, I believe I have successfully created a branch.io session and a listener that will allow me to retrieve data if branchError is null (there are no conflicts)
While still inside onStart() I now try to generate a referral code. So the whole onStart() looks as follows:
#Override
protected void onStart() {
// note that branch is a global variable (Branch branch;)
if (DEBUG) {
branch = Branch.getTestInstance(this.getApplicationContext());
} else {
branch = Branch.getInstance(this.getApplicationContext());
}
branch.initSession(new BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject jsonObject, BranchError branchError) {
if (branchError == null) {}
}, this.getIntent().getData(), this;
}
branch.getReferralCode(5, new BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject jsonObject, BranchError branchError) {
try {
String code = jsonObject.getString("referral_code");
Log.d(TAG, "code: " + code);
} catch (JSONException e) {
Log.e(TAG, "JSONException :: " + e);
e.printStackTrace();
}
}
});
}
5) I added onNewIntent override method
#Override
protected void onNewIntent(Intent intent) {
this.setIntent(intent);
}
My app does not reach inside of the onInitFinished listener, so I am unable to retrieve any code(s). Any suggestions on what I have missed is appreciated, and hopefully this thread will fill the holes that the documentation lacks.
I'm going to assume that the following lines of code are properly closed and aren't throwing syntax errors:
branch.initSession(new BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject jsonObject, BranchError branchError) {
if (branchError == null) {}
}, this.getIntent().getData(), this); // parenthesis wasnt here
First, if you are extending the Application class, you need to initialize branch inside the onCreate() callback of your Application class:
public void onCreate() {
super.onCreate();
Branch.getInstance(this);
}
As per the Branch sample code found here, you actually need to call:
Branch.getInstance();
Instead of:
Branch.getInstance(getApplicationContext());
Inside your activities onCreate callback. Once that is taken care of, the Branch SDK will properly create.

Categories

Resources