com.facebook.GraphResponse Java Examples
The following examples show how to use
com.facebook.GraphResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FbLoginHiddenActivity.java From SocialLoginManager with Apache License 2.0 | 6 votes |
@Override public void onCompleted(JSONObject object, GraphResponse response) { try { SocialUser user = new SocialUser(); user.userId = object.getString("id"); user.accessToken = AccessToken.getCurrentAccessToken().getToken(); user.photoUrl = String.format(PHOTO_URL, user.userId); SocialUser.Profile profile = new SocialUser.Profile(); profile.email = object.has("email")? object.getString("email") : ""; profile.name = object.has("name")? object.getString("name"): ""; profile.pageLink = object.has("link")? object.getString("link"): ""; user.profile = profile; SocialLoginManager.getInstance(this).onLoginSuccess(user); } catch (JSONException e) { SocialLoginManager.getInstance(this).onLoginError(e.getCause()); } LoginManager.getInstance().logOut(); finish(); }
Example #2
Source File: Utility.java From kognitivo with Apache License 2.0 | 6 votes |
public static void getGraphMeRequestWithCacheAsync( final String accessToken, final GraphMeRequestWithCacheCallback callback) { JSONObject cachedValue = ProfileInformationCache.getProfileInformation(accessToken); if (cachedValue != null) { callback.onSuccess(cachedValue); return; } GraphRequest.Callback graphCallback = new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { if (response.getError() != null) { callback.onFailure(response.getError().getException()); } else { ProfileInformationCache.putProfileInformation( accessToken, response.getJSONObject()); callback.onSuccess(response.getJSONObject()); } } }; GraphRequest graphRequest = getGraphMeRequestWithCache(accessToken); graphRequest.setCallback(graphCallback); graphRequest.executeAsync(); }
Example #3
Source File: ShareApi.java From kognitivo with Apache License 2.0 | 6 votes |
private void shareLinkContent(final ShareLinkContent linkContent, final FacebookCallback<Sharer.Result> callback) { final GraphRequest.Callback requestCallback = new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { final JSONObject data = response.getJSONObject(); final String postId = (data == null ? null : data.optString("id")); ShareInternalUtility.invokeCallbackWithResults(callback, postId, response); } }; final Bundle parameters = new Bundle(); this.addCommonParameters(parameters, linkContent); parameters.putString("message", this.getMessage()); parameters.putString("link", Utility.getUriString(linkContent.getContentUrl())); parameters.putString("picture", Utility.getUriString(linkContent.getImageUrl())); parameters.putString("name", linkContent.getContentTitle()); parameters.putString("description", linkContent.getContentDescription()); parameters.putString("ref", linkContent.getRef()); new GraphRequest( AccessToken.getCurrentAccessToken(), getGraphPath("feed"), parameters, HttpMethod.POST, requestCallback).executeAsync(); }
Example #4
Source File: FacebookSignUpAdapter.java From aptoide-client-v8 with GNU General Public License v3.0 | 6 votes |
private Single<String> getFacebookEmail(AccessToken accessToken) { return Single.defer(() -> { try { final GraphResponse response = GraphRequest.newMeRequest(accessToken, null) .executeAndWait(); final JSONObject object = response.getJSONObject(); if (response.getError() == null && object != null) { try { return Single.just( object.has("email") ? object.getString("email") : object.getString("id")); } catch (JSONException ignored) { return Single.error( new FacebookSignUpException(FacebookSignUpException.ERROR, "Error parsing email")); } } else { return Single.error(new FacebookSignUpException(FacebookSignUpException.ERROR, "Unknown error(maybe network error when getting user data)")); } } catch (RuntimeException exception) { return Single.error( new FacebookSignUpException(FacebookSignUpException.ERROR, exception.getMessage())); } }) .subscribeOn(Schedulers.io()); }
Example #5
Source File: Home.java From UberClone with MIT License | 6 votes |
private void handleSignInResult(GoogleSignInResult result) { if (result.isSuccess()) { account = result.getSignInAccount(); Common.userID=account.getId(); loadUser(); }else if(isLoggedInFacebook){ GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { String id=object.optString("id"); Common.userID=id; loadUser(); } }); request.executeAsync(); }else{ Common.userID=FirebaseAuth.getInstance().getCurrentUser().getUid(); loadUser(); } }
Example #6
Source File: Home.java From UberClone with MIT License | 6 votes |
private void updateFirebaseToken() { FirebaseDatabase db=FirebaseDatabase.getInstance(); final DatabaseReference tokens=db.getReference(Common.token_tbl); final Token token=new Token(FirebaseInstanceId.getInstance().getToken()); if(FirebaseAuth.getInstance().getUid()!=null) tokens.child(FirebaseAuth.getInstance().getUid()).setValue(token); else if(account!=null) tokens.child(account.getId()).setValue(token); else{ GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { String id = object.optString("id"); tokens.child(id).setValue(token); } }); request.executeAsync(); } }
Example #7
Source File: GetUserCallback.java From edx-app-android with Apache License 2.0 | 6 votes |
public GetUserCallback(final GetUserResponse getUserResponse) { this.getUserResponse = getUserResponse; callback = new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { SocialMember socialMember; try { JSONObject userObj = response.getJSONObject(); if (userObj == null) { logger.warn("Unable to get user json object from facebook graph api."); return; } socialMember = jsonToUser(userObj); } catch (JSONException e) { logger.error(e); return; } GetUserCallback.this.getUserResponse.onCompleted(socialMember); } }; }
Example #8
Source File: DriverHome.java From UberClone with MIT License | 6 votes |
private void handleSignInResult(GoogleSignInResult result) { if (result.isSuccess()) { account = result.getSignInAccount(); Common.userID=account.getId(); loadUser(); }else if(isLoggedInFacebook){ GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { String id=object.optString("id"); Common.userID=id; loadUser(); } }); request.executeAsync(); }else{ Common.userID=FirebaseAuth.getInstance().getCurrentUser().getUid(); loadUser(); } }
Example #9
Source File: DriverHome.java From UberClone with MIT License | 6 votes |
private void updateFirebaseToken() { FirebaseDatabase db=FirebaseDatabase.getInstance(); final DatabaseReference tokens=db.getReference(Common.token_tbl); final Token token=new Token(FirebaseInstanceId.getInstance().getToken()); if(FirebaseAuth.getInstance().getUid()!=null) tokens.child(FirebaseAuth.getInstance().getUid()).setValue(token); else if(account!=null) tokens.child(account.getId()).setValue(token); else{ GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { String id = object.optString("id"); tokens.child(id).setValue(token); } }); request.executeAsync(); } }
Example #10
Source File: LoginDialogFragment.java From openshop.io-android with MIT License | 5 votes |
@Override public void onSuccess(final LoginResult loginResult) { Timber.d("FB login success"); if (loginResult == null) { Timber.e("Fb login succeed with null loginResult."); handleNonFatalError(getString(R.string.Facebook_login_failed), true); } else { Timber.d("Result: %s", loginResult.toString()); GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { if (response != null && response.getError() == null) { verifyUserOnApi(object, loginResult.getAccessToken()); } else { Timber.e("Error on receiving user profile information."); if (response != null && response.getError() != null) { Timber.e(new RuntimeException(), "Error: %s", response.getError().toString()); } handleNonFatalError(getString(R.string.Receiving_facebook_profile_failed), true); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,gender"); request.setParameters(parameters); request.executeAsync(); } }
Example #11
Source File: FBLoginInstance.java From ShareLoginPayUtil with Apache License 2.0 | 5 votes |
@SuppressLint("CheckResult") @Override public void fetchUserInfo(final BaseToken token) { Bundle params = new Bundle(); params.putString("fields", "picture,name,id,email,permissions"); request = new GraphRequest(((FacebookToken) token).getAccessTokenBean(), "/me", params, HttpMethod.GET, new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { try { if (response != null && response.getJSONObject() != null) { ShareLogger.i(response.getJSONObject().toString()); FacebookUser faceBookUser = new FacebookUser(response.getJSONObject()); mLoginListener.loginSuccess(new LoginResultData(LoginPlatform.FACEBOOK, token, faceBookUser)); } else { mLoginListener.loginFailure(new JSONException("解析GraphResponse异常!!"), 303); } LoginUtil.recycle(); } catch (JSONException e) { e.printStackTrace(); } } }); request.executeAsync(); }
Example #12
Source File: LoginMaster.java From uPods-android with Apache License 2.0 | 5 votes |
private void fetchFacebookUserData(final IOperationFinishWithDataCallback profileFetched) { GraphRequest request = GraphRequest.newMeRequest( AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { userProfile = new UserProfile(); try { StringBuilder userName = new StringBuilder(); if (object.has("first_name")) { userName.append(object.getString("first_name")); } if (object.has("last_name")) { userName.append(" "); userName.append(object.getString("last_name")); } userProfile.setName(userName.toString()); String avatarUrl = "https://graph.facebook.com/" + object.getString("id") + "/picture?type=large"; userProfile.setProfileImageUrl(avatarUrl); profileFetched.operationFinished(userProfile); } catch (Exception e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,first_name,email,last_name"); request.setParameters(parameters); request.executeAsync(); }
Example #13
Source File: FacebookHelper.java From AndroidBlueprints with Apache License 2.0 | 5 votes |
/** * Get requested user data from Facebook */ private void getUserProfile(final Activity activity) { GraphRequest request = GraphRequest.newMeRequest(mLoginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { // Get facebook data from login parseFacebookUserData(activity, object); } }); Bundle parameters = new Bundle(); String[] params = {FACEBOOK_USER_ID, FACEBOOK_USER_FIRST_NAME, FACEBOOK_USER_LAST_NAME, FACEBOOK_USER_EMAIL, FACEBOOK_USER_BIRTHDAY, FACEBOOK_USER_GENDER, FACEBOOK_USER_LOCATION, FACEBOOK_USER_IMAGE_URL}; parameters.putString("fields", createStringParams(params)); request.setParameters(parameters); request.executeAsync(); }
Example #14
Source File: FacebookHelper.java From argus-android with Apache License 2.0 | 5 votes |
public void logout() { if (AccessToken.getCurrentAccessToken() == null) { return; // already logged out } new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest .Callback() { @Override public void onCompleted(GraphResponse graphResponse) { LoginManager.getInstance().logOut(); } }).executeAsync(); }
Example #15
Source File: FacebookHelper.java From argus-android with Apache License 2.0 | 5 votes |
public void initialize() { LoginManager.getInstance() .registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest graphRequest = GraphRequest .newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { token = AccessToken.getCurrentAccessToken(); if (resultListener != null) { resultListener.onSuccess(token); } } }); Bundle parameters = new Bundle(); graphRequest.setParameters(parameters); graphRequest.executeAsync(); } @Override public void onCancel() { } @Override public void onError(FacebookException error) { resultListener.onFailure(error.getMessage()); } }); }
Example #16
Source File: FacebookNetwork.java From EasyLogin with MIT License | 5 votes |
private void addEmailToToken(final AccessToken fbAccessToken) { GraphRequest meRequest = GraphRequest.newMeRequest( fbAccessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject me, GraphResponse response) { final String token = fbAccessToken.getToken(); final String userId = fbAccessToken.getUserId(); if (response.getError() != null) { Log.d("FacebookNetwork", "Error occurred while fetching Facebook email"); accessToken = new com.maksim88.easylogin.AccessToken.Builder(token) .userId(userId) .build(); listener.onLoginSuccess(getNetwork()); } else { final String email = me.optString(EMAIL_PERMISSION_FIELD); final String name = me.optString(NAME_FIELD); if (TextUtils.isEmpty(email)) { Log.d("FacebookNetwork", "Email could not be fetched. The user might not have an email or have unchecked the checkbox while connecting."); } accessToken = new com.maksim88.easylogin.AccessToken.Builder(token) .userId(userId) .email(email) .userName(name) .build(); listener.onLoginSuccess(getNetwork()); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", NAME_FIELD + "," + EMAIL_PERMISSION_FIELD); meRequest.setParameters(parameters); meRequest.executeAsync(); }
Example #17
Source File: Utility.java From kognitivo with Apache License 2.0 | 5 votes |
public static JSONObject awaitGetGraphMeRequestWithCache( final String accessToken) { JSONObject cachedValue = ProfileInformationCache.getProfileInformation(accessToken); if (cachedValue != null) { return cachedValue; } GraphRequest graphRequest = getGraphMeRequestWithCache(accessToken); GraphResponse response = graphRequest.executeAndWait(); if (response.getError() != null) { return null; } return response.getJSONObject(); }
Example #18
Source File: ImportFriendsHelper.java From q-municate-android with Apache License 2.0 | 5 votes |
private void getFacebookFriendsList() { GraphRequest requestFriends = GraphRequest.newMyFriendsRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONArrayCallback() { @Override public void onCompleted(JSONArray objects, GraphResponse response) { Log.d("ImportFriendsHelper", objects.toString()); if (objects.length() > 0) { for (int i = 0; i < objects.length(); i ++) { try { JSONObject elementFriend = (JSONObject) objects.get(i); String userId = elementFriend.getString("id"); String userName = elementFriend.getString("name"); String userLink = elementFriend.getString("link"); friendsFacebookList.add(new InviteFriend(userId, userName, userLink, InviteFriend.VIA_FACEBOOK_TYPE, null, false)); } catch (JSONException e) { e.printStackTrace(); } } fiendsReceived(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,link"); requestFriends.setParameters(parameters); requestFriends.executeAsync(); }
Example #19
Source File: LoginClient.java From kognitivo with Apache License 2.0 | 5 votes |
/** * This parses a server response to a call to me/permissions. It will return the list of * granted permissions. It will optionally update an access token with the requested permissions. * * @param response The server response * @return A list of granted permissions or null if an error */ private static PermissionsPair handlePermissionResponse(GraphResponse response) { if (response.getError() != null) { return null; } JSONObject result = response.getJSONObject(); if (result == null) { return null; } JSONArray data = result.optJSONArray("data"); if (data == null || data.length() == 0) { return null; } List<String> grantedPermissions = new ArrayList<String>(data.length()); List<String> declinedPermissions = new ArrayList<String>(data.length()); for (int i = 0; i < data.length(); ++i) { JSONObject object = data.optJSONObject(i); String permission = object.optString("permission"); if (permission == null || permission.equals("installed")) { continue; } String status = object.optString("status"); if (status == null) { continue; } if(status.equals("granted")) { grantedPermissions.add(permission); } else if (status.equals("declined")) { declinedPermissions.add(permission); } } return new PermissionsPair(grantedPermissions, declinedPermissions); }
Example #20
Source File: VideoUploader.java From kognitivo with Apache License 2.0 | 5 votes |
protected void executeGraphRequestSynchronously(Bundle parameters) { GraphRequest request = new GraphRequest( uploadContext.accessToken, String.format(Locale.ROOT, "%s/videos", uploadContext.graphNode), parameters, HttpMethod.POST, null); GraphResponse response = request.executeAndWait(); if (response != null) { FacebookRequestError error = response.getError(); JSONObject responseJSON = response.getJSONObject(); if (error != null) { if (!attemptRetry(error.getSubErrorCode())) { handleError(new FacebookGraphResponseException(response, ERROR_UPLOAD)); } } else if (responseJSON != null) { try { handleSuccess(responseJSON); } catch (JSONException e) { endUploadWithFailure(new FacebookException(ERROR_BAD_SERVER_RESPONSE, e)); } } else { handleError(new FacebookException(ERROR_BAD_SERVER_RESPONSE)); } } else { handleError(new FacebookException(ERROR_BAD_SERVER_RESPONSE)); } }
Example #21
Source File: ShareInternalUtility.java From kognitivo with Apache License 2.0 | 5 votes |
static void invokeOnErrorCallback( FacebookCallback<Sharer.Result> callback, GraphResponse response, String message) { logShareResult(AnalyticsEvents.PARAMETER_SHARE_OUTCOME_ERROR, message); if (callback != null) { callback.onError(new FacebookGraphResponseException(response, message)); } }
Example #22
Source File: ShareInternalUtility.java From kognitivo with Apache License 2.0 | 5 votes |
public static void invokeCallbackWithResults( FacebookCallback<Sharer.Result> callback, final String postId, final GraphResponse graphResponse) { FacebookRequestError requestError = graphResponse.getError(); if (requestError != null) { String errorMessage = requestError.getErrorMessage(); if (Utility.isNullOrEmpty(errorMessage)) { errorMessage = "Unexpected error sharing."; } invokeOnErrorCallback(callback, graphResponse, errorMessage); } else { invokeOnSuccessCallback(callback, postId); } }
Example #23
Source File: FacebookSignUpActivity.java From socialmediasignup with MIT License | 5 votes |
@Override public void onCompleted(JSONObject object, GraphResponse response) { SocialMediaUser user = new SocialMediaUser(); user.setUserId(object.optString("id")); user.setAccessToken(AccessToken.getCurrentAccessToken().getToken()); user.setProfilePictureUrl(String.format(PROFILE_PIC_URL, user.getUserId())); user.setEmail(object.optString("email")); user.setFullName(object.optString("name")); user.setPageLink(object.optString("link")); loadingDialog.dismiss(); handleSuccess(SocialMediaSignUp.SocialMediaType.FACEBOOK, user); }
Example #24
Source File: FirebaseHelper.java From UberClone with MIT License | 5 votes |
public void registerByFacebookAccount(){ AccessToken accessToken = AccessToken.getCurrentAccessToken(); GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { final String name=object.optString("name"); final String id=object.optString("id"); final String email=object.optString("email"); final User user=new User(); users.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { User post = dataSnapshot.child(id).getValue(User.class); if(post==null) showRegisterPhone(user, id, name, email); else loginSuccess(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); request.executeAsync(); }
Example #25
Source File: FirebaseHelper.java From UberClone with MIT License | 5 votes |
public void registerByFacebookAccount(){ AccessToken accessToken = AccessToken.getCurrentAccessToken(); GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { final String name=object.optString("name"); final String id=object.optString("id"); final String email=object.optString("email"); final User user=new User(); users.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { User post = dataSnapshot.child(id).getValue(User.class); if(post==null) showRegisterPhone(user, id, name, email); else loginSuccess(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); request.executeAsync(); }
Example #26
Source File: FaceBookManager.java From FimiX8-RE with MIT License | 5 votes |
public void login(Context context, final LoginCallback callback) { this.loginCallback = callback; this.mCallbackManager = Factory.create(); FacebookSdk.sdkInitialize(context); this.loginManager = LoginManager.getInstance(); this.loginManager.registerCallback(this.mCallbackManager, new FacebookCallback<LoginResult>() { public void onSuccess(LoginResult loginResult) { GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphJSONObjectCallback() { public void onCompleted(JSONObject object, GraphResponse response) { Log.i(FaceBookManager.TAG, "onCompleted: "); if (object != null) { Map<String, String> map = new HashMap(); map.put("name", object.optString("name")); map.put(BlockInfo.KEY_UID, object.optString("id")); FaceBookManager.this.loginCallback.loginSuccess(map); } } }).executeAsync(); } public void onCancel() { Log.i(FaceBookManager.TAG, "onCancel: "); } public void onError(FacebookException error) { Log.i(FaceBookManager.TAG, "onError: "); callback.loginFail(error.getMessage()); } }); LoginManager.getInstance().logInWithReadPermissions((Activity) context, Arrays.asList(new String[]{"public_profile", "user_friends"})); }
Example #27
Source File: LoginManager.java From kognitivo with Apache License 2.0 | 4 votes |
private LoginClient.Request createLoginRequestFromResponse(final GraphResponse response) { Validate.notNull(response, "response"); AccessToken failedToken = response.getRequest().getAccessToken(); return createLoginRequest(failedToken != null ? failedToken.getPermissions() : null); }
Example #28
Source File: AppEventsLogger.java From kognitivo with Apache License 2.0 | 4 votes |
private static void handleResponse( AccessTokenAppIdPair accessTokenAppId, GraphRequest request, GraphResponse response, SessionEventsState sessionEventsState, FlushStatistics flushState) { FacebookRequestError error = response.getError(); String resultDescription = "Success"; FlushResult flushResult = FlushResult.SUCCESS; if (error != null) { final int NO_CONNECTIVITY_ERROR_CODE = -1; if (error.getErrorCode() == NO_CONNECTIVITY_ERROR_CODE) { resultDescription = "Failed: No Connectivity"; flushResult = FlushResult.NO_CONNECTIVITY; } else { resultDescription = String.format("Failed:\n Response: %s\n Error %s", response.toString(), error.toString()); flushResult = FlushResult.SERVER_ERROR; } } if (FacebookSdk.isLoggingBehaviorEnabled(LoggingBehavior.APP_EVENTS)) { String eventsJsonString = (String) request.getTag(); String prettyPrintedEvents; try { JSONArray jsonArray = new JSONArray(eventsJsonString); prettyPrintedEvents = jsonArray.toString(2); } catch (JSONException exc) { prettyPrintedEvents = "<Can't encode events for debug logging>"; } Logger.log(LoggingBehavior.APP_EVENTS, TAG, "Flush completed\nParams: %s\n Result: %s\n Events JSON: %s", request.getGraphObject().toString(), resultDescription, prettyPrintedEvents); } sessionEventsState.clearInFlightAndStats(error != null); if (flushResult == FlushResult.NO_CONNECTIVITY) { // We may call this for multiple requests in a batch, which is slightly inefficient // since in principle we could call it once for all failed requests, but the impact is // likely to be minimal. We don't call this for other server errors, because if an event // failed because it was malformed, etc., continually retrying it will cause subsequent // events to not be logged either. PersistedEvents.persistEvents(applicationContext, accessTokenAppId, sessionEventsState); } if (flushResult != FlushResult.SUCCESS) { // We assume that connectivity issues are more significant to report than server issues. if (flushState.result != FlushResult.NO_CONNECTIVITY) { flushState.result = flushResult; } } }
Example #29
Source File: ShareApi.java From kognitivo with Apache License 2.0 | 4 votes |
private void sharePhotoContent(final SharePhotoContent photoContent, final FacebookCallback<Sharer.Result> callback) { final Mutable<Integer> requestCount = new Mutable<Integer>(0); final AccessToken accessToken = AccessToken.getCurrentAccessToken(); final ArrayList<GraphRequest> requests = new ArrayList<GraphRequest>(); final ArrayList<JSONObject> results = new ArrayList<JSONObject>(); final ArrayList<GraphResponse> errorResponses = new ArrayList<GraphResponse>(); final GraphRequest.Callback requestCallback = new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { final JSONObject result = response.getJSONObject(); if (result != null) { results.add(result); } if (response.getError() != null) { errorResponses.add(response); } requestCount.value -= 1; if (requestCount.value == 0) { if (!errorResponses.isEmpty()) { ShareInternalUtility.invokeCallbackWithResults( callback, null, errorResponses.get(0)); } else if (!results.isEmpty()) { final String postId = results.get(0).optString("id"); ShareInternalUtility.invokeCallbackWithResults( callback, postId, response); } } } }; try { for (SharePhoto photo : photoContent.getPhotos()) { final Bitmap bitmap = photo.getBitmap(); final Uri photoUri = photo.getImageUrl(); String caption = photo.getCaption(); if (caption == null) { caption = this.getMessage(); } if (bitmap != null) { requests.add(GraphRequest.newUploadPhotoRequest( accessToken, getGraphPath(PHOTOS_EDGE), bitmap, caption, photo.getParameters(), requestCallback)); } else if (photoUri != null) { requests.add(GraphRequest.newUploadPhotoRequest( accessToken, getGraphPath(PHOTOS_EDGE), photoUri, caption, photo.getParameters(), requestCallback)); } } requestCount.value += requests.size(); for (GraphRequest request : requests) { request.executeAsync(); } } catch (final FileNotFoundException ex) { ShareInternalUtility.invokeCallbackWithException(callback, ex); } }
Example #30
Source File: ShareApi.java From kognitivo with Apache License 2.0 | 4 votes |
private void shareOpenGraphContent(final ShareOpenGraphContent openGraphContent, final FacebookCallback<Sharer.Result> callback) { // In order to create a new Open Graph action using a custom object that does not already // exist (objectID or URL), you must first send a request to post the object and then // another to post the action. If a local image is supplied with the object or action, that // must be staged first and then referenced by the staging URL that is returned by that // request. final GraphRequest.Callback requestCallback = new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse response) { final JSONObject data = response.getJSONObject(); final String postId = (data == null ? null : data.optString("id")); ShareInternalUtility.invokeCallbackWithResults(callback, postId, response); } }; final ShareOpenGraphAction action = openGraphContent.getAction(); final Bundle parameters = action.getBundle(); this.addCommonParameters(parameters, openGraphContent); if (!Utility.isNullOrEmpty(this.getMessage())) { parameters.putString("message", this.getMessage()); } final CollectionMapper.OnMapperCompleteListener stageCallback = new CollectionMapper .OnMapperCompleteListener() { @Override public void onComplete() { try { handleImagesOnAction(parameters); new GraphRequest( AccessToken.getCurrentAccessToken(), getGraphPath( URLEncoder.encode(action.getActionType(), DEFAULT_CHARSET)), parameters, HttpMethod.POST, requestCallback).executeAsync(); } catch (final UnsupportedEncodingException ex) { ShareInternalUtility.invokeCallbackWithException(callback, ex); } } @Override public void onError(FacebookException exception) { ShareInternalUtility.invokeCallbackWithException(callback, exception); } }; this.stageOpenGraphAction(parameters, stageCallback); }