com.facebook.GraphRequest Java Examples

The following examples show how to use com.facebook.GraphRequest. 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: DriverHome.java    From UberClone with MIT License 6 votes vote down vote up
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 #2
Source File: DriverHome.java    From UberClone with MIT License 6 votes vote down vote up
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 #3
Source File: GetUserCallback.java    From edx-app-android with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: Home.java    From UberClone with MIT License 6 votes vote down vote up
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 #5
Source File: Home.java    From UberClone with MIT License 6 votes vote down vote up
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: Utility.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: ShareInternalUtility.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new Request configured to upload an image to create a staging resource. Staging
 * resources allow you to post binary data such as images, in preparation for a post of an Open
 * Graph object or action which references the image. The URI returned when uploading a staging
 * resource may be passed as the image property for an Open Graph object or action.
 *
 * @param accessToken the access token to use, or null
 * @param file        the file containing the image to upload
 * @param callback    a callback that will be called when the request is completed to handle
 *                    success or error conditions
 * @return a Request that is ready to execute
 * @throws FileNotFoundException
 */
public static GraphRequest newUploadStagingResourceWithImageRequest(
        AccessToken accessToken,
        File file,
        Callback callback
) throws FileNotFoundException {
    ParcelFileDescriptor descriptor =
            ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    GraphRequest.ParcelableResourceWithMimeType<ParcelFileDescriptor> resourceWithMimeType =
            new GraphRequest.ParcelableResourceWithMimeType<>(descriptor, "image/png");
    Bundle parameters = new Bundle(1);
    parameters.putParcelable(STAGING_PARAM, resourceWithMimeType);

    return new GraphRequest(
            accessToken,
            MY_STAGING_RESOURCES,
            parameters,
            HttpMethod.POST,
            callback);
}
 
Example #8
Source File: FacebookSignUpAdapter.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
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 #9
Source File: ShareApi.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: FacebookNetwork.java    From EasyLogin with MIT License 5 votes vote down vote up
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 #11
Source File: Utility.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
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 #12
Source File: FacebookHelper.java    From argus-android with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: FacebookHelper.java    From argus-android with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: FacebookHelper.java    From AndroidBlueprints with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #15
Source File: LoginMaster.java    From uPods-android with Apache License 2.0 5 votes vote down vote up
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 #16
Source File: FbLoginHiddenActivity.java    From SocialLoginManager with Apache License 2.0 5 votes vote down vote up
@Override
public void onSuccess(LoginResult loginResult) {
  if (!SocialLoginManager.getInstance(this).isWithProfile()) {
    handleLoginSuccess(loginResult);
    finish();
    return;
  }

  GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), this);
  Bundle parameters = new Bundle();
  parameters.putString("fields", "id,name,email,link");
  request.setParameters(parameters);
  request.executeAsync();
}
 
Example #17
Source File: LoginDialogFragment.java    From openshop.io-android with MIT License 5 votes vote down vote up
@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 #18
Source File: FacebookSignInHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onSuccess(LoginResult result) {
    setResult(Resource.<IdpResponse>forLoading());

    GraphRequest request = GraphRequest.newMeRequest(result.getAccessToken(),
            new ProfileRequest(result));

    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,email,picture");
    request.setParameters(parameters);
    request.executeAsync();
}
 
Example #19
Source File: UserRequest.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
public static void makeUserRequest(GraphRequest.Callback callback) {
    final Bundle params = new Bundle();
    params.putString("fields", "name,id,email");
    final GraphRequest request = new GraphRequest(
            AccessToken.getCurrentAccessToken(),
            ME_ENDPOINT,
            params,
            HttpMethod.GET,
            callback
    );
    request.executeAsync();
}
 
Example #20
Source File: ImportFriendsHelper.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: ShareInternalUtility.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Request configured to upload an image to create a staging resource. Staging
 * resources allow you to post binary data such as images, in preparation for a post of an Open
 * Graph object or action which references the image. The URI returned when uploading a staging
 * resource may be passed as the image property for an Open Graph object or action.
 *
 * @param accessToken the access token to use, or null
 * @param imageUri    the file:// or content:// Uri pointing to the image to upload
 * @param callback    a callback that will be called when the request is completed to handle
 *                    success or error conditions
 * @return a Request that is ready to execute
 * @throws FileNotFoundException
 */
public static GraphRequest newUploadStagingResourceWithImageRequest(
        AccessToken accessToken,
        Uri imageUri,
        Callback callback
) throws FileNotFoundException {
    if (Utility.isFileUri(imageUri)) {
        return newUploadStagingResourceWithImageRequest(
                accessToken,
                new File(imageUri.getPath()),
                callback);
    } else if (!Utility.isContentUri(imageUri)) {
        throw new FacebookException("The image Uri must be either a file:// or content:// Uri");
    }

    GraphRequest.ParcelableResourceWithMimeType<Uri> resourceWithMimeType =
            new GraphRequest.ParcelableResourceWithMimeType<>(imageUri, "image/png");
    Bundle parameters = new Bundle(1);
    parameters.putParcelable(STAGING_PARAM, resourceWithMimeType);

    return new GraphRequest(
            accessToken,
            MY_STAGING_RESOURCES,
            parameters,
            HttpMethod.POST,
            callback);
}
 
Example #22
Source File: FBLoginInstance.java    From ShareLoginPayUtil with Apache License 2.0 5 votes vote down vote up
@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 #23
Source File: FirebaseHelper.java    From UberClone with MIT License 5 votes vote down vote up
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 #24
Source File: FirebaseHelper.java    From UberClone with MIT License 5 votes vote down vote up
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: FacebookSignUpActivity.java    From socialmediasignup with MIT License 5 votes vote down vote up
@Override
public void onSuccess(LoginResult loginResult) {
    startLoading();
    GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), this);
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,email,link");
    request.setParameters(parameters);
    request.executeAsync();
}
 
Example #26
Source File: ShareInternalUtility.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Request configured to upload an image to create a staging resource. Staging
 * resources allow you to post binary data such as images, in preparation for a post of an Open
 * Graph object or action which references the image. The URI returned when uploading a staging
 * resource may be passed as the image property for an Open Graph object or action.
 *
 * @param accessToken the access token to use, or null
 * @param image       the image to upload
 * @param callback    a callback that will be called when the request is completed to handle
 *                    success or error conditions
 * @return a Request that is ready to execute
 */
public static GraphRequest newUploadStagingResourceWithImageRequest(
        AccessToken accessToken,
        Bitmap image,
        Callback callback) {
    Bundle parameters = new Bundle(1);
    parameters.putParcelable(STAGING_PARAM, image);

    return new GraphRequest(
            accessToken,
            MY_STAGING_RESOURCES,
            parameters,
            HttpMethod.POST,
            callback);
}
 
Example #27
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
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 #28
Source File: Utility.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private static JSONObject getAppSettingsQueryResponse(String applicationId) {
    Bundle appSettingsParams = new Bundle();
    appSettingsParams.putString(APPLICATION_FIELDS, TextUtils.join(",", APP_SETTING_FIELDS));

    GraphRequest request = GraphRequest.newGraphPathRequest(null, applicationId, null);
    request.setSkipClientToken(true);
    request.setParameters(appSettingsParams);

    return request.executeAndWait().getJSONObject();
}
 
Example #29
Source File: FaceBookManager.java    From FimiX8-RE with MIT License 5 votes vote down vote up
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 #30
Source File: Utility.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private static GraphRequest getGraphMeRequestWithCache(
        final String accessToken) {
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,first_name,middle_name,last_name,link");
    parameters.putString("access_token", accessToken);
    GraphRequest graphRequest = new GraphRequest(
            null,
            "me",
            parameters,
            HttpMethod.GET,
            null);
    return graphRequest;
}