Having trouble using facebook graph API library for android when sending a batch of requests.
Not getting a callback when running this code:
RequestBatch requestBatch = new RequestBatch(requests);
requestBatch.addCallback(new com.facebook.RequestBatch.Callback() {
#Override
public void onBatchCompleted(RequestBatch batch) {
Log.e(LOG_TAG, "onBatchCompleted()");
}
});
requestBatch.executeAsync();
Found the answer.
You need to set the callback for each individual request to get the batch-related callback, because onBatchCompleted callback will be called after all per-Request callbacks are called..
for (String friend : friends) {
MyLog.d(LOG_TAG, "Adding request for " + friend.getInterestFbId());
String graphPath = friend + "/feed";
Request request = new Request(session, graphPath, null, HttpMethod.GET);
Bundle params = new Bundle();
params.putString("fields",
"id,"+
"name,"+
"username,"+
"feed,");
request.setParameters(params);
// THIS IS VITAL OR THE BATCH CALLBACK WILL NEVER ARRIVE
request.setCallback(new com.facebook.Request.Callback() {
#Override
public void onCompleted(Response response) {}
});
requests.add(request);
}
Related
I'm trying to get the facebook's user's timeline in my Android app.
Here my code :
mLoginButton.setReadPermissions(Arrays.asList("user_about_me", "user_friends", "user_likes",
"user_photos", "user_relationships", "user_posts",
"user_status"));
// If using in a fragment
mLoginButton.setFragment(this);
// Other app specific specialization
// Callback registration
mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
mAccessToken = loginResult.getAccessToken();
for (String permission : loginResult.getRecentlyGrantedPermissions()) {
Log.d(LOG_TAG, "Granted Permission:" + permission);
}
getUserFeed();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
And after the login, I launch this :
private void getUserFeed() {
Bundle params = new Bundle();
params.putInt("limit", 25);
params.putString("fields", "id,name,link,full_picture,message,story,picture,type,place,from,to");
params.putBoolean("summary", true);
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/home",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
final JSONArray data = response.getJSONObject().getJSONArray("data");
//currentJson = response.getJSONObject();
} catch (JSONException e) {
Log.e("Error: ", e.toString());
}
}
}
).executeAsync();
}
I have this respond code from Facebook :
Requires extended permission: read_stream
I know this permission is depreceted, I'm using the latest API 2.5.
Do you know if we can continue to get the user's timeline now, if I replace the "/me/home" by "/me/feed" it's ok, but I just get my posts, not my entire timeline.
Thanks :)
Do you know if we can continue to get the user's timeline now,
No, you can’t.
if I replace the "/me/home" by "/me/feed" it's ok, but I just get my posts, not my entire timeline.
/me/home was deprecated together with the permission.
/me/feed is what you can get now, and that’s it.
Which posts you can expect to see is listed here: https://developers.facebook.com/docs/graph-api/reference/v2.5/user/feed#readperms
I have show facebook feeds(post) list in may application. I am using facebook 4.0 I am able to get profile but unable to fetch all my feeds(post). If anybody have any reference then please tell me. Thanks.
Right-now I am using following code for get Feeds but getting blank response like {"data":[]}
FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
loginResult.getAccessToken().getUserId()+"/feed/",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.i("fb", "Feeds :" +response.getJSONObject());
Toast.makeText(
getApplicationContext(),
response.getJSONObject()
+ "",
Toast.LENGTH_SHORT).show();
}
}
).executeAsync();
}
You need to make a graph api call from within your app https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed
Here,
You are not passing parameters like these:
Bundle params = new Bundle();
params.putString("fields", "message,created_time,id,full_picture,status_type,source,comments.summary(true),likes.summary(true)");
params.putString("limit", "10");
/* make the API call */
new GraphRequest(AccessToken.getCurrentAccessToken(), "/userId/posts", params, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
System.out.println("Festival Page response::" + String.valueOf(response.getJSONObject()));
try {
JSONObject jObjResponse = new JSONObject(String.valueOf(response.getJSONObject()));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
).executeAsync();
Hope to solving these issue i am solving into facebook SDK 4.6.0
You should add the user_posts permission to your login request:
LoginManager.getInstance().logInWithReadPermissions(this,
Arrays.asList("public_profile ", "user_status","user_posts"));
I am using Facebook SDK and Parse SDK and I want to retrieve the profile cover picture.
I am doing the following:
new Request(
ParseFacebookUtils.getSession(),
"/me?fields=cover",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
Log.wtf("TAG",
response.toString());
}
}).executeAsync();
But I am not able to get the proper response since it says I need an access token (the user has already been logged in).
{Response:
responseCode: 400,
graphObject: null,
error: {
HttpStatus: 400,
errorCode: 2500,
errorType: OAuthException,
errorMessage: An active access token must be used to query information about the current user.
},
isFromCache:false
}
Is there any fix for this available?
After spending A LOT of hours searching for the answer, I finally got it !!!
The Android SDK for Facebook docs, are too useless.
To solve this problem we just need to set the Graph Path in the second param and a Bundle with fields as third param. Example:
Bundle params = new Bundle();
params.putString("fields", "cover");
new Request(ParseFacebookUtils.getSession(),
"me",
params,
HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
//code...
}
}).executeAsync();
Then we can parse the response object returned in onCompleted as JSON with
response.getGraphObject().getInnerJsonObject();
//or
response.getGraphObject().getProperty("cover");
Source: New Facebook SDK and OAuthException in Graphpath requests thanks to #Jesse Chen
Facebook changed a few things and has some terrible documentation. Hope this helps someone else it's what worked for me.
public void getCoverPhotoFB(final String email, AccessToken accessToken){
if(!AccessToken.getCurrentAccessToken().getPermissions().contains("user_photos")) {
Log.e(L, "getCoverPhotoFB....get user_photo permission");
LoginManager.getInstance().logInWithReadPermissions(
this,
Arrays.asList("user_photos"));
}
////
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("fields", "cover");
new GraphRequest(
accessToken,
"me",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(final GraphResponse response) {
Log.e(L, "getCoverPhotoFB..."+response);
// thread is necessary for network call
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String picUrlString = (String) response.getJSONObject().getJSONObject("cover").get("source");
Log.d(L,"getCoverPhotoFB.....picURLString....."+picUrlString);
URL img_value = new URL(picUrlString);
Bitmap eventBitmap = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
saveImageToExternalStorage(eventBitmap, email + "_B.png");
homeProfile(profile, email);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
thread.start();
}
}
).executeAsync();
}
Im trying to upgrade to the Facebook SDK 3.0 and have finally gotten everything to work with Request.newStatusUpdateRequest(). However my app shares/posts text along with a link. I have tried/looked into the following:
Request.newStatusUpdateRequest()
This does not seem to have any options for a Bundle or any other way to include a link and icon.
Request.newRestRequest()
Skipped this because I saw REST was being depreciated.
new WebDialog.FeedDialogBuilder(_activity, session, params).build().show();
This actually works pretty well but the resulting post does not seem to be linked to my Facebook App and I am not sure how this will effect my Facebook insights.
Request.newPostRequest()
From what I have read, this method seems to be the proper way. However, i cannot figure out where to get the GraphObject to pass in as one of the parameters.
What is the PROPPER way to post/share text, link and image to the user's wall? It seems to be Request.newPostRequest() so I will include the code I have for that.
Request request = Request.newPostRequest(session, "me/feed", ??graph_object??, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult("message", response.getGraphObject(), response.getError());
}
});
request.setParameters(params);
Request.executeBatchAsync(request);
But what really is a GraphObject? Where do i get the graph_object? The more I read from FB on GraphObject/OpenGraph/Graph API the more I get confused.
If I am heading down the wrong direction entirely, please tell me. If Request.newPostRequest is the propper way of doing this, please give me more information on the GraphObject param.
Finally managed to get everything I needed with the Facebook SDK 3.0 using the following:
Bundle params = new Bundle();
params.putString("caption", "caption");
params.putString("message", "message");
params.putString("link", "link_url");
params.putString("picture", "picture_url");
Request request = new Request(Session.getActiveSession(), "me/feed", params, HttpMethod.POST);
request.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response.getError() == null) {
// Tell the user success!
}
}
});
request.executeAsync();
I did by using this method.
See if this can help or not.
public static void publishFeedDialog(final Activity current, final String title,
final String caption, final String description, final String link,
final String pictureUrl) {
// start Facebook Login
Session.openActiveSession(current, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
Bundle params = new Bundle();
params.putString("name", title);
params.putString("caption", caption);
params.putString("description", description);
params.putString("link", link);
params.putString("picture", pictureUrl);
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
current, Session.getActiveSession(), params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the
// success
// and the post Id.
final String postId = values
.getString("post_id");
if (postId != null) {
ToastHelper.MakeShortText("Posted");
} else {
// User clicked the Cancel button
ToastHelper
.MakeShortText("Publish cancelled");
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
ToastHelper
.MakeShortText("Publish cancelled");
} else {
// Generic, ex: network error
ToastHelper
.MakeShortText("Error posting story");
}
}
}).build();
feedDialog.show();
}
}
});
To share page or link
Bundle params = new Bundle();
params.putString("link", "link_url");
Request request = new Request(Session.getActiveSession(), "me/feed", params, HttpMethod.POST);
request.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response.getError() == null) {
// Tell the user success!
}
}
});
request.executeAsync();
For more post parameters see me/feed on developer.facebook.com
I am developing an android application which includes the facebook integration. If I execute multiple fql queries, I am getting the response in changed order.
I am using the following code:
public static ArrayList<String> photoAlbumIdArr = null;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
photoAlbumIdArr = new ArrayList<String>();
photoAlbumIdArr.add("111114545_25133454545");
photoAlbumIdArr.add("111114590_25133434768");
photoAlbumIdArr.add("111114232_2513345487");
photoAlbumIdArr.add("111114512_25133454456");
startProgress();
}
public void startProgress() {
// Do something long
PhotoGalleryActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
String fqlQuery = "";
for(int k=0;k<photoAlbumIdArr.size();k++)
{
fqlQuery = "SELECT pid, src FROM photo WHERE aid = '"+photoAlbumIdArr.get(k)+"'";
Bundle params = new Bundle();
params.putString("q", fqlQuery);
session = Session.getActiveSession();
Request request = new Request(session, "/fql", params,
HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
String jsonResponse = response.toString();
Log.i(LOG_TAG, jsonResponse);
}
});
Request.executeBatchAsync(request);
}
}
});
}
Here the callback response is called after the for loop completed. In that I am getting the unorder response(i.e) getting first album photos as last or middle response likewise. What may be the problem. Why I get the unordered response.
This may be due to the fact that you do not have an ORDER BY clause in your FQL query.
Try using something like:
SELECT pid, src FROM photo WHERE aid = '{album id}' ORDER BY modified
This will ensure that the order that is returned is always the same (assuming no images are modified in-between queries).