I am implementing the new Facebook SDK 3.0.1 and I have some doubts about use with Session.
I created a function to query just the user id:
String userID;
public String getUserID(){
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (session == Session.getActiveSession()) {
if (user != null) {
userID = user.getId();
System.out.println("User ID " + userID); //OK
}
}
}
});
Request.executeBatchAsync(request);
return userID;
}else{
return null;
}
}
The problem is when I do System.out.println("ID is... "+FB.getUserID()); because only shows: "ID is...".
But the internal println perfectly shows the id (User ID XXXXXXXXX). The problem is the time to receive the information. How I can I control it?
I think you cannot control it.
You are executing an async request that is a request that "permits other processing to continue before the transmission has finished." (see Wikipedia page).
You have to wait until the onCompleted method is called by the request object.
There is actually a way around this. Simply use Request.executeAndWait(). that function does exactly what it sounds like it does, it pauses the thread until the onComplete is finished.
Related
I am using Facebook and Parse SDK in my Android app. I followed this tutorial for Facebook login and authentication, changing between fragments for login fragment and main menu fragment depending on whether the session state is OPENED in the Session.StatusCallback. And the app works perfectly before integrating with Parse.
And now I encounter a problem. In the onResume() method of the main menu fragment, I added the following code.
final Session session = Session.getActiveSession();
if(session != null && session.isOpened()) {
Request meRequest = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser graphUser, Response response) {
if(session == Session.getActiveSession()) {
// Check if the session is same as usual
ParseFacebookUtils.logIn(graphUser.getId(), session.getAccessToken(),
session.getExpirationDate(), new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
// The user wasn't saved.
System.out.println("User was not saved to Parse. ");
} else {
// The user has been saved to Parse.
System.out.println("User has successfully been saved to Parse.");
if (user.isNew()) {
// This user was created during this session with Facebook Login.
System.out.println("ParseUser created.");
} else {
// This user existed before.
System.out.println("User exists in Parse. Pull their values: " + user);
}
}
}
});
}
}
});
meRequest.executeAsync();
}
So when the fragment is resumed and the Facebook session is opened, the Facebook user is added to the Parse database so that I can use ParseUser to put and get data afterwards. But the problem happens when using ParseFacebookUtils.logIn(), that it makes the Facebook session CLOSED and invokes the Session.StatusCallback, thus switching the visible fragment back to the login fragment.
I was dealing with this problem all day but cannot find a solution. I have added the code below in an Application but still not work.
Parse.enableLocalDatastore(this);
Parse.initialize(this, Application_id, Client_key);
ParseFacebookUtils.initialize(getString(R.string.facebook_app_id));
Is there a way to fix this? I have read this but no quite good solution is provided. Thanks in advance!
I was trying to do the same thing today. I was using the facebook sdk's UiLifecycleHelper to do the facebook login, make the graph api request and add the user to Parse db. That is how it is done in the example you mentioned - which I think is a bit outdated.
ParseFacebookUtils handles the session and all we need to do is call the login method on it, make the graph api call, get user data like email and update the user field.
Here's some code:
private void parseFacebookLogin(){
ParseFacebookUtils.logIn(this, PARSE_FB_LOGIN_CODE, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d(tag, "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d(tag, "User signed up and logged in through Facebook!");
Request.newMeRequest(ParseFacebookUtils.getSession(), graphUserCallback).executeAsync();
} else {
Log.d(tag, "User logged in through Facebook!");
}
}
});
}
GraphUserCallback graphUserCallback = new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null){
getUserDataFacebook(user);
Log.d(tag, response.toString());
}
}
};
private void getUserDataFacebook(GraphUser user){
//get user data here
}
Check out Parse's docs on Facebook login.
Let me know if this works for you.
I have a big problem with android-facebook-sdk 3.19.1. No problem to retrieve public information about user but it is not possible getting email address.
I know my post is very near to the following thread ==> facebook android sdk -user email returns null but I have no solution for now.
So here is my code
In my ConnectionActivity.java I have a button R.id.fb_connect
private List<String> permissions = Arrays.asList("email");
#Click(R.id.fb_connect)
protected void fbConnect() {
ensureOpenSession();
}
private boolean ensureOpenSession() {
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
LOGD(TAG, "Call Session.openActiveSession");
Session.openActiveSession(this, true, permissions, new FbCallback());
return false;
}
return true;
}
public class FbCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState sessionState, Exception e) {
// 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) {
// user.asMap().get("email");
Toast.makeText(ConnectionActivity.this, "email : " + user.getProperty("email"), Toast.LENGTH_LONG).show();
}
}
}).executeAsync();
}
}
I've also tried the code in the link above but it doesn't work. One precision, with this code, I can see the facebook activity which says "XXX will receive the following info: your public profile and email address" but the toast displays "email : null"
EDIT
I work with android studio and my gradle file has the following line
compile 'com.facebook.android:facebook-android-sdk:3.19.1'
EDIT2
If I use
LOGD(TAG, "isPermissionGranted : " + session.isPermissionGranted(permissions.get(0)));
before call Request.newMeRequest so true is shown. Permission is correctly granted
Thx
I'm trying to follow scrumptious tutorial, at the part of newMeRequest, the request never returns, the code is as in the example, like below. Am I missing anything? thanks?
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (BuildConfig.DEBUG){
Log.i(TAG, "GraphUserCallback" + user.getId()+" " + response.toString());
}
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
//profilePictureView.setProfileId(user.getId());
profilePictureView.setId(Integer.parseInt(user.getId()));
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
Make sure you add this permission
<uses-permission android:name="android.permission.INTERNET"/>
here is my code for updating status:
new Session(context);
Session.setActiveSession(session);
Session.openActiveSession(context);
Log.e("session after setted",Session.getActiveSession().toString());
Request request = Request.newMeRequest(Session.getActiveSession(), new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (Session.getActiveSession().isOpened()) {
if (user != null) {
session = Session.getActiveSession();
postFromAlarm();
Log.e("user","not null");
}else{
postFromAlarm();
Log.e("user","null");
}
} else{
postFromAlarm();
Log.e("not open session",Session.getActiveSession().toString());
Log.e("session","not open");
}
}
});
Log.e("request session",request.getSession().toString());
Request.executeBatchAsync(request);
Log.e("session after setted",Session.getActiveSession().toString());
is showing a good and healthy session, which can be used for posting. because in logcat, it is showing that the session is open, accesstoken is good, app_id is also good.
but using this session when i am trying to post, in the onComplete() method, executed these lines:
Log.e("not open session",Session.getActiveSession().toString());
Log.e("session","not open");
and it is showing that:
{Session state:CLOSED, token:null, appId:***************** }
what is wrong? i have tried without new Session(context), but getting the same result. what should i do?
save the session when you create it for first time using
SessionStore.save(mFacebook, getBaseContext());
and also restore the session when same user performs post operation
SessionStore.restore(mFacebook, getBaseContext());
where mFacebook is your Facebook object reference
Here's what's happening:
My program updates when there is a state change
The handler for the state change needs to know the user's ID before proceeding; it calls findUserID()
findUserID() requests the user's ID from the Facebook Graph API
The handler for the state change proceeds before that value if found and therefor behaves incorrectly.
A few seconds later, the trace (Log.d) displays that the user's ID has been found
If I pause and then resume my program, the user ID is noticed and then my program behaves correctly; however, this should NOT need to be done. How do I make my program wait for the Facebook Graph API's response before proceeding?
protected void findUserID(Session session)
{
//userId = null; // Set initial
// If session is open
if (session != null && session.isOpened()) {
// Make an API call to get user data
// and define a new callback to handle the response
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
Session session = Session.getActiveSession();
// If current session matches active session
if (session == Session.getActiveSession()) {
if (user != null) {
userId = user.getId(); // set userId
Log.d("internal", "UserId issss: " + userId);
} // end if user != null
} // end if session == Session.getActiveSession()
} // end onCompleted
}); // end request
Request.executeBatchAsync(request); // Request does not execute unless you call this.
Log.d("findUserID", "The value after request: " + userId);
} // end session open check
}
Any/all help is appreciated.
The code inside the onCompleted method is a "callback". It gets invoked asynchronously when the Facebook request is completed. The original function findUserID will have already returned by then. Using callbacks takes some getting used to, and it requires you to organize your flow of control accordingly. Instead of returning a value from a function, you should make a "onUserIdFound" function and call that when the userID is found.
use some ..executeAndWait method on Request class instead of executeBatchAsync, than your program should wait for data and after that it will proceed...
take a look here: https://developers.facebook.com/docs/reference/android/3.0/Request