com.facebook.Response Java Examples

The following examples show how to use com.facebook.Response. 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: LoginActivity.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void call(Session session, SessionState state, Exception exception) {
	if (session.isOpened()) {
		setFacebookSession(session);
		// make request to the /me API
		Request.newMeRequest(session, new Request.GraphUserCallback() {

			// callback after Graph API response with user object
			@Override
			public void onCompleted(GraphUser user, Response response) {
				if (user != null) {
					Toast.makeText(LoginActivity.this,
							"Hello " + user.getName(), Toast.LENGTH_LONG)
							.show();
				}
			}
		}).executeAsync();
	}
}
 
Example #2
Source File: FacebookContactMatcher.java    From buddycloud-android with Apache License 2.0 6 votes vote down vote up
private void matchContacts(final Context context, final GraphUser user, 
		Response response, final ModelCallback<JSONArray> callback) {
	JSONArray friends = response.getGraphObject()
			.getInnerJSONObject().optJSONArray("data");
	JSONArray friendsHashes = new JSONArray();
	for (int i = 0; i < friends.length(); i++) {
		String friendId = friends.optString(i, "id");
		String friendHash = ContactMatcherUtils.hash(NAME, friendId);
		friendsHashes.put(friendHash);
	}
	
	JSONArray myHashes = new JSONArray();
	myHashes.put(user.getId());
	
	ContactMatcherUtils.reportToFriendFinder(context, callback, 
			friendsHashes, myHashes);
}
 
Example #3
Source File: FiscalizacaoConcluidaActivity.java    From vocefiscal-android with Apache License 2.0 5 votes vote down vote up
private void publishStory(Session session) 
{
	Bundle postParams = new Bundle();
	postParams.putString("name", "Você Fiscal");

	// Receber os dados da eleição!!!
	postParams.putString("message", "Eu fiscalizei a seção: "+ this.secao +"\nNa zona eleitoral: " + this.zonaEleitoral + "\nNo município de: " + this.municipio);			
	postParams.putString("description", "Obrigado por contribuir com a democracia!");
	postParams.putString("link", "http://www.vocefiscal.org/");
	postParams.putString("picture", "http://imagizer.imageshack.us/v2/150x100q90/913/bAwPgx.png");

	Request.Callback callback= new Request.Callback() 
	{
		public void onCompleted(Response response) 
		{
			JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
			String postId = "Compartilhado com sucesso!";
			try 
			{
				postId = graphResponse.getString("Compartilhado com sucesso!");
			} catch (JSONException e) 
			{
			}
			FacebookRequestError error = response.getError();
			if (error != null) 
			{
				Toast.makeText(FiscalizacaoConcluidaActivity.this.getApplicationContext(),error.getErrorMessage(),Toast.LENGTH_SHORT).show();
			} else 
			{
				Toast.makeText(FiscalizacaoConcluidaActivity.this.getApplicationContext(),	postId,	Toast.LENGTH_LONG).show();
			}
		}
	};

	Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);

	RequestAsyncTask task = new RequestAsyncTask(request);
	task.execute();
}
 
Example #4
Source File: LoginButton.java    From Klyph with MIT License 5 votes vote down vote up
private void fetchUserInfo() {
    if (fetchUserInfo) {
        final Session currentSession = sessionTracker.getOpenSession();
        if (currentSession != null) {
            if (currentSession != userInfoSession) {
                Request request = Request.newMeRequest(currentSession, new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser me,  Response response) {
                        if (currentSession == sessionTracker.getOpenSession()) {
                            user = me;
                            if (userInfoChangedCallback != null) {
                                userInfoChangedCallback.onUserInfoFetched(user);
                            }
                        }
                        if (response.getError() != null) {
                            handleError(response.getError().getException());
                        }
                    }
                });
                Request.executeBatchAsync(request);
                userInfoSession = currentSession;
            }
        } else {
            user = null;
            if (userInfoChangedCallback != null) {
                userInfoChangedCallback.onUserInfoFetched(user);
            }
        }
    }
}
 
Example #5
Source File: FlowApiRequests.java    From flow-android with MIT License 5 votes vote down vote up
public static void getUserCoverImage(final Context context, final String fbid, final ImageView imageView, final FlowImageLoaderCallback callback){
    Bundle params = new Bundle();
    params.putString("fields", "cover");
    new Request(
            Session.getActiveSession(),
            "/" + fbid,
            params,
            HttpMethod.GET,
            new Request.Callback() {
                public void onCompleted(Response response) {
                    GraphObject graphObject = response.getGraphObject();
                    if (graphObject != null && graphObject.getProperty("cover") != null) {
                        if (graphObject != null && graphObject.getProperty("cover") != null) {
                            try {
                                JSONObject json = graphObject.getInnerJSONObject();
                                String url = json.getJSONObject("cover").getString("source");
                                FlowImageLoader loader = new FlowImageLoader(context);
                                loader.loadImage(url, imageView, callback);
                            } catch (Exception e) {
                                Crashlytics.logException(e);
                            }
                        }
                    }
                }
            }
    ).executeAsync();
}
 
Example #6
Source File: FacebookShareActivity.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
private void postImageToFacebook() {
    Session session = Session.getActiveSession();
    final Uri uri = (Uri) mExtras.get(Intent.EXTRA_STREAM);
    final String extraText = mPostTextView.getText().toString();
    if (session.isPermissionGranted("publish_actions"))
    {
        Bundle param = new Bundle();

        // Add the image
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] byteArrayData = stream.toByteArray();
            param.putByteArray("picture", byteArrayData);
        } catch (IOException ioe) {
            // The image that was send through is now not there?
            Assert.assertTrue(false);
        }

        // Add the caption
        param.putString("message", extraText);
        Request request = new Request(session,"me/photos", param, HttpMethod.POST, new Request.Callback() {
            @Override
            public void onCompleted(Response response) {
                addNotification(getString(R.string.photo_post), response.getGraphObject(), response.getError());

            }
        }, null);
        RequestAsyncTask asyncTask = new RequestAsyncTask(request);
        asyncTask.execute();
        finish();
    }
}
 
Example #7
Source File: LoginButton.java    From KlyphMessenger with MIT License 5 votes vote down vote up
private void fetchUserInfo() {
    if (fetchUserInfo) {
        final Session currentSession = sessionTracker.getOpenSession();
        if (currentSession != null) {
            if (currentSession != userInfoSession) {
                Request request = Request.newMeRequest(currentSession, new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser me,  Response response) {
                        if (currentSession == sessionTracker.getOpenSession()) {
                            user = me;
                            if (userInfoChangedCallback != null) {
                                userInfoChangedCallback.onUserInfoFetched(user);
                            }
                        }
                        if (response.getError() != null) {
                            handleError(response.getError().getException());
                        }
                    }
                });
                Request.executeBatchAsync(request);
                userInfoSession = currentSession;
            }
        } else {
            user = null;
            if (userInfoChangedCallback != null) {
                userInfoChangedCallback.onUserInfoFetched(user);
            }
        }
    }
}
 
Example #8
Source File: FacebookGraphAPIRequestTask.java    From FacebookNewsfeedSample-Android with Apache License 2.0 5 votes vote down vote up
/**
 * This is the method performing all of this Tasks' work. It loops through all of the {@link com.dhsoftware.android.FacebookNewsfeedSample.model.GraphAPIRequest GraphAPIRequest}s and
 * adds all the downloaded items into a list.
 */
@Override
protected Void doInBackground(GraphAPIRequest... params) {
   mItems = new ArrayList<INewsfeedItem>();
   final Session session = Session.getActiveSession();
   for (GraphAPIRequest request : params) {
      Request graphApiRequest = Request.newGraphPathRequest(session, request.getGraphPath(), null);
      graphApiRequest.setParameters(request.getParameters());
      // this call blocks the calling thread, but in this case it's OK, since we're already in a background thread
      // in this way, you can see both uses of making requests to the Facebook API
      Response response = graphApiRequest.executeAndWait();
      // we could also check here that our Session's valid; which is recommended in Facebook's own samples
      // in this sample's case, I check it in MyNewsfeedFragment just before adding the downloaded items to the Adapter
      if (response != null) {
         // if we did get a response, we
         processResponse(response.getGraphObject().getInnerJSONObject());
      }

   }

   // We sort all items we've downloaded from newest to oldest,
   // in this way, the items will fill in naturally to how we display
   // Newsfeed items.
   Collections.sort(mItems, new Comparator<INewsfeedItem>() {
      @Override
      public int compare(INewsfeedItem lhs, INewsfeedItem rhs) {
         DateTime lhsDateTime = new DateTime(lhs.getCreated_Time());
         DateTime rhsDateTime = new DateTime(rhs.getCreated_Time());
         return (lhsDateTime.compareTo(rhsDateTime));
      }
   });

   // this is not the method returning the objects,
   // since we're still running in a background thread
   return null;
}
 
Example #9
Source File: FacebookContactMatcher.java    From buddycloud-android with Apache License 2.0 5 votes vote down vote up
private void getFriends(final Context context, final Session session, 
		final ModelCallback<JSONArray> callback) {
	Request.newMeRequest(session, new GraphUserCallback() {
		@Override
		public void onCompleted(final GraphUser user, Response response) {
			if (response.getError() != null) {
				callback.error(response.getError().getException());
				return;
			}
			getFriends(context, session, user, callback);
		}
	}).executeAsync();
}
 
Example #10
Source File: FacebookContactMatcher.java    From buddycloud-android with Apache License 2.0 5 votes vote down vote up
protected void getFriends(final Context context, final Session session, 
		final GraphUser user, final ModelCallback<JSONArray> callback) {
	Request.newGraphPathRequest(session, "/me/friends", new Callback() {
		@Override
		public void onCompleted(Response response) {
			if (response.getError() != null) {
				callback.error(response.getError().getException());
				return;
			}
			matchContacts(context, user, response, callback);
		}
	}).executeAsync();
}
 
Example #11
Source File: FragmentSocialTimeline.java    From aptoide-client with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    Logger.d("FragmentSocialTimeline", " onCreate");
    super.onCreate(savedInstanceState);
    if (savedInstanceState == null) {
        init();
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {

        fbhelper = new UiLifecycleHelper(getActivity(), new Session.StatusCallback() {
            @Override
            public void call(final Session session, SessionState state, Exception exception) {
                if (!AptoideUtils.AccountUtils.isLoggedIn(Aptoide.getContext()) || removeAccount) {
                    try {
                        final AccountManager mAccountManager = AccountManager.get(getActivity());

                        if (session.isOpened()) {
                            Request.newMeRequest(session, new Request.GraphUserCallback() {
                                @Override
                                public void onCompleted(final GraphUser user, Response response) {

                                    if (removeAccount && mAccountManager.getAccountsByType(Aptoide.getConfiguration().getAccountType()).length > 0) {
                                        mAccountManager.removeAccount(mAccountManager.getAccountsByType(Aptoide.getConfiguration().getAccountType())[0], new AccountManagerCallback<Boolean>() {
                                            @Override
                                            public void run(AccountManagerFuture<Boolean> future) {
                                                startLogin(user, session);
                                            }
                                        }, new Handler(Looper.getMainLooper()));
                                    } else {

                                        startLogin(user, session);
                                    }
                                }
                            }).executeAsync();

                        }
                    } catch (Exception e) {
                        Toast.makeText(Aptoide.getContext(), R.string.error_occured, Toast.LENGTH_LONG).show();
                        loginError();
                    }
                }
            }
        });

        fbhelper.onCreate(savedInstanceState);
    }
}
 
Example #12
Source File: LoginActivity.java    From aptoide-client with GNU General Public License v2.0 4 votes vote down vote up
public void submit(final Mode mode, final String userName, final String passwordOrToken, final String nameForGoogle) {
    Log.d(TAG, "Submitting. mode: " + mode.name() +", userName: " + userName + ", nameForGoogle: " + nameForGoogle);
    final String accountType = getIntent().getStringExtra(ARG_ACCOUNT_TYPE);

    OAuth2AuthenticationRequest oAuth2AuthenticationRequest = new OAuth2AuthenticationRequest();
    oAuth2AuthenticationRequest.setPassword(passwordOrToken);
    oAuth2AuthenticationRequest.setUsername(userName);
    oAuth2AuthenticationRequest.setMode(mode);
    oAuth2AuthenticationRequest.setNameForGoogle(nameForGoogle);

    setShowProgress(true);
    spiceManager.execute(oAuth2AuthenticationRequest, new RequestListener<OAuth>() {
        @Override
        public void onRequestFailure(SpiceException spiceException) {
            Log.d(TAG, "OAuth filed: " + spiceException.getMessage());
            final Throwable cause = spiceException.getCause();
            if (cause != null) {
                final String error;
                if (cause instanceof RetrofitError) {
                    final RetrofitError retrofitError = (RetrofitError) cause;
                    final retrofit.client.Response response = retrofitError.getResponse();
                    if (response != null && (response.getStatus() == 400 || response.getStatus() == 401)) {
                        error = getString(R.string.error_AUTH_1);
                    } else {
                        error = getString(R.string.error_occured);
                    }
                } else {
                    error = getString(R.string.error_occured);
                }
                Toast.makeText(getBaseContext(), error, Toast.LENGTH_SHORT).show();
            }
            setShowProgress(false);
        }

        @Override
        public void onRequestSuccess(final OAuth oAuth) {
            if (oAuth.getStatus() != null && oAuth.getStatus().equals("FAIL")) {
                Log.d(TAG, "OAuth filed: " + oAuth.getError_description());
                AptoideUtils.UI.toastError(oAuth.getError());
                setShowProgress(false);
            } else {
                getUserInfo(oAuth, userName, mode, accountType, passwordOrToken);
                Analytics.Login.login(userName, mode);
            }
        }
    });
}