com.facebook.FacebookException Java Examples

The following examples show how to use com.facebook.FacebookException. 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: Login.java    From UberClone with MIT License 7 votes vote down vote up
private void setupFacebookStuff() {

        // This should normally be on your application class
        FacebookSdk.sdkInitialize(getApplicationContext());

        mLoginManager = LoginManager.getInstance();
        mFacebookCallbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(mFacebookCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                //login
                firebaseHelper.registerByFacebookAccount();
            }

            @Override
            public void onCancel() {
                Toast.makeText(Login.this,"The login was canceled",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(Login.this,"There was an error in the login",Toast.LENGTH_SHORT).show();
            }
        });
    }
 
Example #2
Source File: ShareInternalUtility.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
public static void registerSharerCallback(
        final int requestCode,
        final CallbackManager callbackManager,
        final FacebookCallback<Sharer.Result> callback) {
    if (!(callbackManager instanceof CallbackManagerImpl)) {
        throw new FacebookException("Unexpected CallbackManager, " +
                "please use the provided Factory.");
    }

    ((CallbackManagerImpl) callbackManager).registerCallback(
            requestCode,
            new CallbackManagerImpl.Callback() {
                @Override
                public boolean onActivityResult(int resultCode, Intent data) {
                    return handleActivityResult(
                            requestCode,
                            resultCode,
                            data,
                            getShareResultProcessor(callback));
                }
            });
}
 
Example #3
Source File: NativeProtocol.java    From letv with Apache License 2.0 6 votes vote down vote up
public static FacebookException getExceptionFromErrorData(Bundle errorData) {
    if (errorData == null) {
        return null;
    }
    String type = errorData.getString(BRIDGE_ARG_ERROR_TYPE);
    if (type == null) {
        type = errorData.getString(STATUS_ERROR_TYPE);
    }
    String description = errorData.getString(BRIDGE_ARG_ERROR_DESCRIPTION);
    if (description == null) {
        description = errorData.getString(STATUS_ERROR_DESCRIPTION);
    }
    if (type == null || !type.equalsIgnoreCase(ERROR_USER_CANCELED)) {
        return new FacebookException(description);
    }
    return new FacebookOperationCanceledException(description);
}
 
Example #4
Source File: LoginManager.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
/**
 * Registers a login callback to the given callback manager.
 * @param callbackManager The callback manager that will encapsulate the callback.
 * @param callback The login callback that will be called on login completion.
 */
public void registerCallback(
        final CallbackManager callbackManager,
        final FacebookCallback<LoginResult> callback) {
    if (!(callbackManager instanceof CallbackManagerImpl)) {
        throw new FacebookException("Unexpected CallbackManager, " +
                "please use the provided Factory.");
    }
    ((CallbackManagerImpl) callbackManager).registerCallback(
            CallbackManagerImpl.RequestCodeOffset.Login.toRequestCode(),
            new CallbackManagerImpl.Callback() {
                @Override
                public boolean onActivityResult(int resultCode, Intent data) {
                    return LoginManager.this.onActivityResult(
                            resultCode,
                            data,
                            callback);
                }
            }
    );
}
 
Example #5
Source File: LoginClient.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
void authorize(Request request) {
    if (request == null) {
        return;
    }

    if (pendingRequest != null) {
        throw new FacebookException("Attempted to authorize while a request is pending.");
    }

    if (AccessToken.getCurrentAccessToken() != null && !checkInternetPermission()) {
        // We're going to need INTERNET permission later and don't have it, so fail early.
        return;
    }
    pendingRequest = request;
    handlersToTry = getHandlersToTry(request);
    tryNextHandler();
}
 
Example #6
Source File: WebDialogParameters.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
public static Bundle create(ShareOpenGraphContent shareOpenGraphContent) {
    Bundle params = new Bundle();

    Utility.putNonEmptyString(
            params,
            ShareConstants.WEB_DIALOG_PARAM_ACTION_TYPE,
            shareOpenGraphContent.getAction().getActionType());

    try {
        JSONObject ogJSON = ShareInternalUtility.toJSONObjectForWeb(shareOpenGraphContent);
        ogJSON = ShareInternalUtility.removeNamespacesFromOGJsonObject(ogJSON, false);
        if (ogJSON != null) {
            Utility.putNonEmptyString(
                    params,
                    ShareConstants.WEB_DIALOG_PARAM_ACTION_PROPERTIES,
                    ogJSON.toString());
        }
    } catch (JSONException e) {
        throw new FacebookException("Unable to serialize the ShareOpenGraphContent to JSON", e);
    }

    return params;
}
 
Example #7
Source File: FacebookAuth.java    From edx-app-android with Apache License 2.0 6 votes vote down vote up
public FacebookAuth(Activity activity) {
    super(activity);
    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    if (callback != null) {
                        callback.onLogin(loginResult.getAccessToken().getToken());
                    }
                    logger.debug("Facebook Logged in successfully.");
                }

                @Override
                public void onCancel() {
                    logger.debug("Facebook Log in canceled.");
                }

                @Override
                public void onError(FacebookException error) {
                    logger.error(error);
                }
            });
}
 
Example #8
Source File: FireSignin.java    From Learning-Resources with MIT License 6 votes vote down vote up
private void signInFacebook() {

        mPrgrsbrMain.setVisibility(View.VISIBLE);
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
        LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                // Facebook Sign In was successful, authenticate with Firebase
                firebaseAuthWithFacebook(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                LogManager.printLog(LOGTYPE_DEBUG, "facebook:onCancel");
                mPrgrsbrMain.setVisibility(View.GONE);
            }

            @Override
            public void onError(FacebookException error) {
                Log.d(LOG_TAG, "facebook:onError", error);
                mPrgrsbrMain.setVisibility(View.GONE);
            }
        });
    }
 
Example #9
Source File: DialogPresenter.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
public static void setupAppCallForErrorResult(AppCall appCall, FacebookException exception) {
    if (exception == null) {
        return;
    }
    Validate.hasFacebookActivity(FacebookSdk.getApplicationContext());

    Intent errorResultIntent = new Intent();
    errorResultIntent.setClass(FacebookSdk.getApplicationContext(), FacebookActivity.class);
    errorResultIntent.setAction(FacebookActivity.PASS_THROUGH_CANCEL_ACTION);

    NativeProtocol.setupProtocolRequestIntent(
            errorResultIntent,
            appCall.getCallId().toString(),
            null,
            NativeProtocol.getLatestKnownVersion(),
            NativeProtocol.createBundleForException(exception));

    appCall.setRequestIntent(errorResultIntent);
}
 
Example #10
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private void initialize()
        throws FileNotFoundException {
    ParcelFileDescriptor fileDescriptor = null;
    try {
        if (Utility.isFileUri(videoUri)) {
            fileDescriptor = ParcelFileDescriptor.open(
                    new File(videoUri.getPath()),
                    ParcelFileDescriptor.MODE_READ_ONLY);
            videoSize = fileDescriptor.getStatSize();
            videoStream = new ParcelFileDescriptor.AutoCloseInputStream(fileDescriptor);
        } else if (Utility.isContentUri(videoUri)) {
            videoSize = Utility.getContentSize(videoUri);
            videoStream = FacebookSdk
                    .getApplicationContext()
                    .getContentResolver()
                    .openInputStream(videoUri);
        } else {
            throw new FacebookException("Uri must be a content:// or file:// uri");
        }
    } catch (FileNotFoundException e) {
        Utility.closeQuietly(videoStream);

        throw e;
    }
}
 
Example #11
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
@Override
public Bundle getParameters()
        throws IOException {
    Bundle parameters = new Bundle();
    parameters.putString(PARAM_UPLOAD_PHASE, PARAM_VALUE_UPLOAD_TRANSFER_PHASE);
    parameters.putString(PARAM_SESSION_ID, uploadContext.sessionId);
    parameters.putString(PARAM_START_OFFSET, chunkStart);

    byte[] chunk = getChunk(uploadContext, chunkStart, chunkEnd);
    if (chunk != null) {
        parameters.putByteArray(PARAM_VIDEO_FILE_CHUNK, chunk);
    } else {
        throw new FacebookException("Error reading video");
    }

    return parameters;
}
 
Example #12
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 6 votes vote down vote up
private static void issueResponse(
        final UploadContext uploadContext,
        final FacebookException error,
        final String videoId) {
    // Remove the UploadContext synchronously
    // Once the UploadContext is removed, this is the only reference to it.
    removePendingUpload(uploadContext);

    Utility.closeQuietly(uploadContext.videoStream);

    if (uploadContext.callback != null) {
        if (error != null) {
            ShareInternalUtility.invokeOnErrorCallback(uploadContext.callback, error);
        } else if (uploadContext.isCanceled) {
            ShareInternalUtility.invokeOnCancelCallback(uploadContext.callback);
        } else {
            ShareInternalUtility.invokeOnSuccessCallback(uploadContext.callback, videoId);
        }
    }
}
 
Example #13
Source File: LoginActivity.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
private void initFacebookSignIn() {
    mCallbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            LogUtil.logDebug(TAG, "facebook:onSuccess:" + loginResult);
            presenter.handleFacebookSignInResult(loginResult);
        }

        @Override
        public void onCancel() {
            LogUtil.logDebug(TAG, "facebook:onCancel");
        }

        @Override
        public void onError(FacebookException error) {
            LogUtil.logError(TAG, "facebook:onError", error);
            showSnackBar(error.getMessage());
        }
    });

    findViewById(R.id.facebookSignInButton).setOnClickListener(v -> presenter.onFacebookSignInClick());
}
 
Example #14
Source File: ProfilePictureView.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
private void processResponse(ImageResponse response) {
    // First check if the response is for the right request. We may have:
    // 1. Sent a new request, thus super-ceding this one.
    // 2. Detached this view, in which case the response should be discarded.
    if (response.getRequest() == lastRequest) {
        lastRequest = null;
        Bitmap responseImage = response.getBitmap();
        Exception error = response.getError();
        if (error != null) {
            OnErrorListener listener = onErrorListener;
            if (listener != null) {
                listener.onError(new FacebookException(
                        "Error in downloading profile picture for profileId: " + getProfileId(), error));
            } else {
                Logger.log(LoggingBehavior.REQUESTS, Log.ERROR, TAG, error.toString());
            }
        } else if (responseImage != null) {
            setImageBitmap(responseImage);

            if (response.isCachedRedirect()) {
                sendImageRequest(false);
            }
        }
    }
}
 
Example #15
Source File: FacebookHelper.java    From AndroidBlueprints with Apache License 2.0 6 votes vote down vote up
/**
 * Register call back manager.
 *
 * @param activity the activity
 */
private void registerCallBackManager(final Activity activity) {
    LoginManager.getInstance()
            .registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    mLoginResult = loginResult;
                    getUserProfile(activity);
                }

                @Override
                public void onCancel() {
                    mFacebookLoginResultCallBack.onFacebookLoginCancel();
                }

                @Override
                public void onError(FacebookException error) {
                    mFacebookLoginResultCallBack.onFacebookLoginError(error);
                }
            });
}
 
Example #16
Source File: LoginManager.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private void validatePublishPermissions(Collection<String> permissions) {
    if (permissions == null) {
        return;
    }
    for (String permission : permissions) {
        if (!isPublishPermission(permission)) {
            throw new FacebookException(
                String.format(
                    "Cannot pass a read permission (%s) to a request for publish authorization",
                    permission));
        }
    }
}
 
Example #17
Source File: LikeView.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private Activity getActivity() {
    Context context = getContext();
    while (!(context instanceof Activity) && context instanceof ContextWrapper) {
        context = ((ContextWrapper) context).getBaseContext();
    }

    if (context instanceof Activity) {
        return (Activity) context;
    }
    throw new FacebookException("Unable to get Activity.");
}
 
Example #18
Source File: FriendPickerFragment.java    From Abelana-Android with Apache License 2.0 5 votes vote down vote up
@Override
Request getRequestForLoadData(Session session) {
    if (adapter == null) {
        throw new FacebookException("Can't issue requests until Fragment has been created.");
    }

    String userToFetch = (userId != null) ? userId : "me";
    return createRequest(userToFetch, extraFields, session);
}
 
Example #19
Source File: LoginClient.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
void validateSameFbidAndFinish(Result pendingResult) {
    if (pendingResult.token == null) {
        throw new FacebookException("Can't validate without a token");
    }

    AccessToken previousToken = AccessToken.getCurrentAccessToken();
    AccessToken newToken = pendingResult.token;

    try {
        Result result = null;
        if (previousToken != null && newToken != null &&
                previousToken.getUserId().equals(newToken.getUserId())) {
            result = Result.createTokenResult(pendingRequest, pendingResult.token);
        } else {
            result = Result
                    .createErrorResult(
                            pendingRequest,
                            "User logged in as different Facebook user.",
                            null);
        }
        complete(result);
    } catch (Exception ex) {
        complete(Result.createErrorResult(
                pendingRequest,
                "Caught exception",
                ex.getMessage()));
    }
}
 
Example #20
Source File: FriendPickerFragment.java    From android-skeleton-project with MIT License 5 votes vote down vote up
@Override
Request getRequestForLoadData(Session session) {
    if (adapter == null) {
        throw new FacebookException("Can't issue requests until Fragment has been created.");
    }

    String userToFetch = (userId != null) ? userId : "me";
    return createRequest(userToFetch, extraFields, session);
}
 
Example #21
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    if (!uploadContext.isCanceled) {
        try {
            executeGraphRequestSynchronously(getParameters());
        } catch (FacebookException fe) {
            endUploadWithFailure(fe);
        } catch (Exception e) {
            endUploadWithFailure(new FacebookException(ERROR_UPLOAD, e));
        }
    } else {
        // No specific failure here.
        endUploadWithFailure(null);
    }
}
 
Example #22
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 #23
Source File: VideoUploader.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
protected void issueResponseOnMainThread(
        final FacebookException error,
        final String videoId) {
    getHandler().post(new Runnable() {
        @Override
        public void run() {
            issueResponse(uploadContext, error, videoId);
        }
    });
}
 
Example #24
Source File: LoginManager.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
private void finishLogin(
        AccessToken newToken,
        LoginClient.Request origRequest,
        FacebookException exception,
        boolean isCanceled,
        FacebookCallback<LoginResult>  callback) {
    if (newToken != null) {
        AccessToken.setCurrentAccessToken(newToken);
        Profile.fetchProfileForCurrentAccessToken();
    }

    if (callback != null) {
        LoginResult loginResult = newToken != null
                ? computeLoginResult(origRequest, newToken)
                : null;
        // If there are no granted permissions, the operation is treated as cancel.
        if (isCanceled
                || (loginResult != null
                       && loginResult.getRecentlyGrantedPermissions().size() == 0)) {
            callback.onCancel();
        } else if (exception != null) {
            callback.onError(exception);
        } else if (newToken != null) {
            callback.onSuccess(loginResult);
        }
    }
}
 
Example #25
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 #26
Source File: ShareInternalUtility.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
static void invokeOnErrorCallback(
        FacebookCallback<Sharer.Result> callback,
        String message) {
    logShareResult(AnalyticsEvents.PARAMETER_SHARE_OUTCOME_ERROR, message);
    if (callback != null) {
        callback.onError(new FacebookException(message));
    }
}
 
Example #27
Source File: LoginActivity.java    From Simple-Blog-App with MIT License 5 votes vote down vote up
private void fbInit() {

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.d("facebook:token", AccessToken.getCurrentAccessToken().getToken());
                AccessToken.getCurrentAccessToken().getToken();
                signInWithFacebook(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                Log.d(TAG, "facebook:onCancel");
            }

            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "facebook:onError", error);
            }
        });
        fbImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("email", "user_location", "user_birthday", "public_profile", "user_friends"));
            }
        });
    }
 
Example #28
Source File: Utility.java    From facebook-api-android-maven with Apache License 2.0 5 votes vote down vote up
public static void putObjectInBundle(Bundle bundle, String key, Object value) {
    if (value instanceof String) {
        bundle.putString(key, (String) value);
    } else if (value instanceof Parcelable) {
        bundle.putParcelable(key, (Parcelable) value);
    } else if (value instanceof byte[]) {
        bundle.putByteArray(key, (byte[]) value);
    } else {
        throw new FacebookException("attempted to add unsupported type to Bundle");
    }
}
 
Example #29
Source File: Utility.java    From Abelana-Android with Apache License 2.0 5 votes vote down vote up
public static void putObjectInBundle(Bundle bundle, String key, Object value) {
    if (value instanceof String) {
        bundle.putString(key, (String) value);
    } else if (value instanceof Parcelable) {
        bundle.putParcelable(key, (Parcelable) value);
    } else if (value instanceof byte[]) {
        bundle.putByteArray(key, (byte[]) value);
    } else {
        throw new FacebookException("attempted to add unsupported type to Bundle");
    }
}
 
Example #30
Source File: FriendPickerFragment.java    From facebook-api-android-maven with Apache License 2.0 5 votes vote down vote up
@Override
Request getRequestForLoadData(Session session) {
    if (adapter == null) {
        throw new FacebookException("Can't issue requests until Fragment has been created.");
    }

    String userToFetch = (userId != null) ? userId : "me";
    return createRequest(userToFetch, extraFields, session);
}