Java Code Examples for com.facebook.GraphRequest#executeAsync()

The following examples show how to use com.facebook.GraphRequest#executeAsync() . 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: 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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
Source File: LoginActivity.java    From andela-crypto-app with Apache License 2.0 4 votes vote down vote up
private void loadUserData(final LoginResult loginResult) {
    GraphRequest request = GraphRequest.newMeRequest(
            loginResult.getAccessToken(),
            (object, response) -> {

                Timber.i(response.toString());

                // Application code
                try {
                    String name = response.getJSONObject().getString("name");
                    String image_url = "http://graph.facebook.com/" + loginResult.getAccessToken().getUserId() + "/picture?type=large";

                    /*
                     * Save to ObjectBox ORM
                     * Set the Logged in status to true
                     * Navigate user to Main Activity
                     */
                    User user = new User();
                    user.name = name;
                    user.imageUrl = image_url;
                    userBox.put(user);

                    Timber.d("Total Users : %d", userBox.count());

                    Settings.setLoggedInSharedPref(true);
                    Settings.setIsFacebook(true);

                    Intent login = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(login);
                    finish();

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,link");
    request.setParameters(parameters);
    request.executeAsync();
}
 
Example 19
Source File: LoginPresenterImpl.java    From Saude-no-Mapa with MIT License 4 votes vote down vote up
@Override
public void onSuccess(LoginResult loginResult) {
    GraphRequest request = GraphRequest.newMeRequest(
            loginResult.getAccessToken(),
            (object, response) -> {
                Log.d(TAG, "onSuccess: " + object);
                Log.d(TAG, "onSuccess: " + response);
                String email = "";
                String name = "";
                try {
                    name = object.getString("name");
                    email = object.getString("email");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (TextUtils.isEmpty(email)) {
                    // TODO: 28-Jul-16
                } else {
                    if (mIsValidationFromDialog) {
                        mSubscription.add(mInteractor.requestReactivateFacebookAccount(AccessToken.getCurrentAccessToken().getApplicationId() +
                                AccessToken.getCurrentAccessToken().getUserId())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(reactivateObserver));
                    } else {
                        User user = new User();
                        user.setName(name);
                        // TODO: 14/10/2016  
                        user.setEmail("xx" + email);
                        user.setPassword(AccessToken.getCurrentAccessToken().getApplicationId() +
                                AccessToken.getCurrentAccessToken().getUserId() + "xx");
                        user.setPasswordType(User.FACEBOOK_LOGIN_TYPE);
                        mInteractor.saveUserToRealm(user);
                        isFacebook = true;
                        mFirebaseAuth.signInWithEmailAndPassword(user.getEmail(), user.getPassword())
                                .addOnCompleteListener(mContext, task -> {
                                    Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
                                    mSubscription.add(mInteractor.requestLoginWithFacebook(user.getEmail(), user.getPassword())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .subscribe(loginObserver));
                                });
                    }
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,email");
    request.setParameters(parameters);
    request.executeAsync();
}
 
Example 20
Source File: ShareApi.java    From kognitivo with Apache License 2.0 4 votes vote down vote up
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);
    }
}