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.