Search in sources :

Example 11 with GraphResponse

use of com.facebook.GraphResponse in project facebook-android-sdk by facebook.

the class ShareApi method shareOpenGraphContent.

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);
}
Also used : GraphRequest(com.facebook.GraphRequest) Bundle(android.os.Bundle) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FacebookCallback(com.facebook.FacebookCallback) JSONObject(org.json.JSONObject) GraphResponse(com.facebook.GraphResponse) FacebookException(com.facebook.FacebookException) CollectionMapper(com.facebook.internal.CollectionMapper)

Example 12 with GraphResponse

use of com.facebook.GraphResponse in project facebook-android-sdk by facebook.

the class DeviceAuthDialog method startLogin.

public void startLogin(final LoginClient.Request request) {
    this.mRequest = request;
    final Bundle parameters = new Bundle();
    parameters.putString("scope", TextUtils.join(",", request.getPermissions()));
    String redirectUriString = request.getDeviceRedirectUriString();
    if (redirectUriString != null) {
        parameters.putString("redirect_uri", redirectUriString);
    }
    String accessToken = Validate.hasAppID() + "|" + Validate.hasClientToken();
    parameters.putString(GraphRequest.ACCESS_TOKEN_PARAM, accessToken);
    parameters.putString(DeviceRequestsHelper.DEVICE_INFO_PARAM, DeviceRequestsHelper.getDeviceInfo());
    GraphRequest graphRequest = new GraphRequest(null, DEVICE_LOGIN_ENDPOINT, parameters, HttpMethod.POST, new GraphRequest.Callback() {

        @Override
        public void onCompleted(GraphResponse response) {
            if (isBeingDestroyed) {
                return;
            }
            if (response.getError() != null) {
                onError(response.getError().getException());
                return;
            }
            JSONObject jsonObject = response.getJSONObject();
            RequestState requestState = new RequestState();
            try {
                requestState.setUserCode(jsonObject.getString("user_code"));
                requestState.setRequestCode(jsonObject.getString("code"));
                requestState.setInterval(jsonObject.getLong("interval"));
            } catch (JSONException ex) {
                onError(new FacebookException(ex));
                return;
            }
            setCurrentRequestState(requestState);
        }
    });
    graphRequest.executeAsync();
}
Also used : GraphRequest(com.facebook.GraphRequest) JSONObject(org.json.JSONObject) GraphResponse(com.facebook.GraphResponse) Bundle(android.os.Bundle) FacebookException(com.facebook.FacebookException) JSONException(org.json.JSONException)

Example 13 with GraphResponse

use of com.facebook.GraphResponse in project facebook-android-sdk by facebook.

the class UserSettingsFragment method fetchUserInfo.

private void fetchUserInfo() {
    final AccessToken accessToken = AccessToken.getCurrentAccessToken();
    if (accessToken != null) {
        GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {

            @Override
            public void onCompleted(JSONObject me, GraphResponse response) {
                user = me;
                updateUI();
            }
        });
        Bundle parameters = new Bundle();
        parameters.putString(FIELDS, REQUEST_FIELDS);
        request.setParameters(parameters);
        GraphRequest.executeBatchAsync(request);
    } else {
        user = null;
    }
}
Also used : GraphRequest(com.facebook.GraphRequest) JSONObject(org.json.JSONObject) GraphResponse(com.facebook.GraphResponse) AccessToken(com.facebook.AccessToken) Bundle(android.os.Bundle)

Example 14 with GraphResponse

use of com.facebook.GraphResponse in project facebook-android-sdk by facebook.

the class FacebookLoginActivity method onCreate.

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_facebook_login);
    callbackManager = CallbackManager.Factory.create();
    fbLoginButton = (LoginButton) findViewById(R.id._fb_login);
    profilePictureView = (ProfilePictureView) findViewById(R.id.user_pic);
    profilePictureView.setCropped(true);
    userNameView = (TextView) findViewById(R.id.user_name);
    final Button deAuthButton = (Button) findViewById(R.id.deauth);
    deAuthButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (!isLoggedIn()) {
                Toast.makeText(FacebookLoginActivity.this, R.string.app_not_logged_in, Toast.LENGTH_LONG).show();
                return;
            }
            GraphRequest.Callback callback = new GraphRequest.Callback() {

                @Override
                public void onCompleted(GraphResponse response) {
                    try {
                        if (response.getError() != null) {
                            Toast.makeText(FacebookLoginActivity.this, getResources().getString(R.string.failed_to_deauth, response.toString()), Toast.LENGTH_LONG).show();
                        } else if (response.getJSONObject().getBoolean(SUCCESS)) {
                            LoginManager.getInstance().logOut();
                        // updateUI();?
                        }
                    } catch (JSONException ex) {
                    /* no op */
                    }
                }
            };
            GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), GRAPH_PATH, new Bundle(), HttpMethod.DELETE, callback);
            request.executeAsync();
        }
    });
    final Button permsButton = (Button) findViewById(R.id.perms);
    permsButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(final View v) {
            Intent selectPermsIntent = new Intent(FacebookLoginActivity.this, PermissionSelectActivity.class);
            startActivityForResult(selectPermsIntent, PICK_PERMS_REQUEST);
        }
    });
    // Callback registration
    fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

        @Override
        public void onSuccess(final LoginResult loginResult) {
            // App code
            Toast.makeText(FacebookLoginActivity.this, R.string.success, Toast.LENGTH_LONG).show();
            updateUI();
        }

        @Override
        public void onCancel() {
            // App code
            Toast.makeText(FacebookLoginActivity.this, R.string.cancel, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(final FacebookException exception) {
            // App code
            Toast.makeText(FacebookLoginActivity.this, R.string.error, Toast.LENGTH_LONG).show();
        }
    });
    new ProfileTracker() {

        @Override
        protected void onCurrentProfileChanged(final Profile oldProfile, final Profile currentProfile) {
            updateUI();
        }
    };
}
Also used : GraphRequest(com.facebook.GraphRequest) Bundle(android.os.Bundle) LoginResult(com.facebook.login.LoginResult) JSONException(org.json.JSONException) Intent(android.content.Intent) TextView(android.widget.TextView) View(android.view.View) ProfilePictureView(com.facebook.login.widget.ProfilePictureView) Profile(com.facebook.Profile) FacebookCallback(com.facebook.FacebookCallback) ProfileTracker(com.facebook.ProfileTracker) Button(android.widget.Button) LoginButton(com.facebook.login.widget.LoginButton) GraphResponse(com.facebook.GraphResponse) FacebookException(com.facebook.FacebookException)

Example 15 with GraphResponse

use of com.facebook.GraphResponse in project facebook-android-sdk by facebook.

the class FacebookAppLinkResolver method getAppLinkFromUrlsInBackground.

/**
     * Asynchronously resolves App Link data for multiple URLs
     *
     * @param uris A list of Uri objects to resolve into App Links
     * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was
     * successfully resolved into an App Link. Uris that could not be resolved into App Links will
     * not be present in the Map. In the case of general server errors, the task will be completed
     * with the corresponding error.
     */
public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();
    for (Uri uri : uris) {
        AppLink appLink;
        synchronized (cachedAppLinks) {
            appLink = cachedAppLinks.get(uri);
        }
        if (appLink != null) {
            appLinkResults.put(uri, appLink);
        } else {
            if (!urisToRequest.isEmpty()) {
                graphRequestFields.append(',');
            }
            graphRequestFields.append(uri.toString());
            urisToRequest.add(uri);
        }
    }
    if (urisToRequest.isEmpty()) {
        return Task.forResult(appLinkResults);
    }
    final Task<Map<Uri, AppLink>>.TaskCompletionSource<Map<Uri, AppLink>> taskCompletionSource = Task.create();
    Bundle appLinkRequestParameters = new Bundle();
    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString("fields", String.format("%s.fields(%s,%s)", APP_LINK_KEY, APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    GraphRequest appLinkRequest = new GraphRequest(// token
    AccessToken.getCurrentAccessToken(), /* Access Token */
    "", /* Graph path */
    appLinkRequestParameters, /* Query parameters */
    null, /* HttpMethod */
    new GraphRequest.Callback() {

        /* Callback */
        @Override
        public void onCompleted(GraphResponse response) {
            FacebookRequestError error = response.getError();
            if (error != null) {
                taskCompletionSource.setError(error.getException());
                return;
            }
            JSONObject responseJson = response.getJSONObject();
            if (responseJson == null) {
                taskCompletionSource.setResult(appLinkResults);
                return;
            }
            for (Uri uri : urisToRequest) {
                String uriString = uri.toString();
                if (!responseJson.has(uriString)) {
                    continue;
                }
                JSONObject urlData;
                try {
                    urlData = responseJson.getJSONObject(uri.toString());
                    JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);
                    JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);
                    int targetsCount = rawTargets.length();
                    List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);
                    for (int i = 0; i < targetsCount; i++) {
                        AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                        if (target != null) {
                            targets.add(target);
                        }
                    }
                    Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                    AppLink appLink = new AppLink(uri, targets, webFallbackUrl);
                    appLinkResults.put(uri, appLink);
                    synchronized (cachedAppLinks) {
                        cachedAppLinks.put(uri, appLink);
                    }
                } catch (JSONException e) {
                    // The data for this uri was missing or badly formed.
                    continue;
                }
            }
            taskCompletionSource.setResult(appLinkResults);
        }
    });
    appLinkRequest.executeAsync();
    return taskCompletionSource.getTask();
}
Also used : Task(bolts.Task) GraphRequest(com.facebook.GraphRequest) HashMap(java.util.HashMap) Bundle(android.os.Bundle) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) Uri(android.net.Uri) FacebookRequestError(com.facebook.FacebookRequestError) JSONObject(org.json.JSONObject) GraphResponse(com.facebook.GraphResponse) AppLink(bolts.AppLink) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Aggregations

GraphRequest (com.facebook.GraphRequest)19 GraphResponse (com.facebook.GraphResponse)19 JSONObject (org.json.JSONObject)16 Bundle (android.os.Bundle)15 JSONException (org.json.JSONException)11 FacebookException (com.facebook.FacebookException)8 FacebookCallback (com.facebook.FacebookCallback)6 FacebookRequestError (com.facebook.FacebookRequestError)6 AccessToken (com.facebook.AccessToken)4 Uri (android.net.Uri)3 Bitmap (android.graphics.Bitmap)2 FacebookGraphResponseException (com.facebook.FacebookGraphResponseException)2 CollectionMapper (com.facebook.internal.CollectionMapper)2 FileNotFoundException (java.io.FileNotFoundException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Intent (android.content.Intent)1 View (android.view.View)1 Button (android.widget.Button)1 TextView (android.widget.TextView)1 AppLink (bolts.AppLink)1