Can we fetch birth date of user from Android Facebook Sdk? - android

I need to fetch user's birth day from their FB account. I tried this link : Get Date of Birth and Town/City from Facebook SDK GraphUserCallback
But it not help me much. Please let me know is it possible to fetch birth date, or there are any restriction from FB SDk to access this?
Thanks.

First of all you have to specify user_birthday permission while using Facebook SDK and then you can use the below snippet to request for the User Birthday.
Revised code just to give you full demonstration
public void getBirthDate(){
// set permissions
List<String> permissions = new ArrayList<String>();
permissions.add("user_birthday");
Session activeSession = Session.getActiveSession();
Context context=getApplicationContext();
if (activeSession == null || activeSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
// set active session
activeSession = session;
}
// if a session is already open then issue a request using the available
// session. Otherwise ask for user credentials.
if (activeSession.isOpened()) {
// User Logged In
Session.getActiveSession().closeAndClearTokenInformation();
// Open Active Session
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Log.i(LOGTAG, "Json Data that is coming from FB:" + user.getInnerJSONObject());
}
}
});
}
}
});
} else {
//If session is not opened
OpenRequest openRequest = new Session.OpenRequest((Activity) this);
openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
//Setting no call back dealing it in OnAcitivityResult
openRequest.setCallback(null);
//Setting Permission
openRequest.setPermissions(permissions);
activeSession.openForRead(openRequest);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Session activeSession = Session.getActiveSession();
if (activeSession == null || activeSession.getState().isClosed()) {
Session session = new Session.Builder(getApplicationContext()).build();
Session.setActiveSession(session);
activeSession = session;
}
if (activeSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Log.i(LOGTAG, "Json Data that is coming from FB:" + user.getInnerJSONObject());
}
}
});
}
}
});
}
}
Hope this will help you
The JSON callback would look like
{
"id": "146473xxx",
"name": "XYZ",
"first_name": "dkajsd",
"last_name": "kajs",
"link": "https://....",
"username": "xxxx",
"birthday": "12/12/91",
"hometown":
}

Related

android facebook sdk - set permissions for openActiveSession

I am trying to integrate Facebook SDK to an android app. I got the code from Facebook manual. It uses Session.openActiveSession and then request a graph user. How could I request for more permissions without using LoginButton class?
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// got user graph
} else {
// could not get user graph
}
}
});
}
}
});
Thank you.
Try this:
mCallback = new Session.StatusCallback() {...}; // the code you already have
Session.OpenRequest request = new Session.OpenRequest(mContext);
request.setPermissions(Arrays.asList("email", "user_birthday"));
request.setCallback(mCallback );
// get active session
Session mFacebookSession = Session.getActiveSession();
if (mFacebookSession == null || mFacebookSession.isClosed())
{
mFacebookSession = new Session(mContext);
Session.setActiveSession(mFacebookSession);
}
mFacebookSession.openForRead(request);
This solves the problem using opensession and extended persmission just once. Facebook SDK 3.5
Session s = new Session(this);
Session.setActiveSession(s);
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("basic_info","email"));
request.setCallback( new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Toast.makeText(getApplicationContext(), "User email is:"+user.getProperty("email"), Toast.LENGTH_SHORT).show(); }
else {
Toast.makeText(getApplicationContext(), "Error User Null", Toast.LENGTH_SHORT).show();
}
}
}).executeAsync();
}
}
}); //end of call;
s.openForRead(request); //now do the request above

org.json.JSONException: No value for email

while trying to access user details, I am getting this error:
07-29 14:49:47.343: W/System.err(2745): org.json.JSONException: No value for email
07-29 14:49:47.353: W/System.err(2745): at org.json.JSONObject.get(JSONObject.java:354)
07-29 14:49:47.374: W/System.err(2745): at org.json.JSONObject.getString(JSONObject.java:510)
07-29 14:49:47.374: W/System.err(2745): at com.example.healthcity.common.FacebookContainer$3$1.onCompleted(FacebookContainer.java:237)
07-29 14:49:47.409: W/System.err(2745): at com.facebook.Request$1.onCompleted(Request.java:264)
07-29 14:49:47.413: W/System.err(2745): at com.facebook.Request$4.run(Request.java:1240)
07-29 14:49:47.423: W/System.err(2745): at android.os.Handler.handleCallback(Handler.java:725)
07-29 14:49:47.423: W/System.err(2745): at android.os.Handler.dispatchMessage(Handler.java:92)
07-29 14:49:47.433: W/System.err(2745): at android.os.Looper.loop(Looper.java:137)
07-29 14:49:47.444: W/System.err(2745): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-29 14:49:47.444: W/System.err(2745): at java.lang.reflect.Method.invokeNative(Native Method)
07-29 14:49:47.463: W/System.err(2745): at java.lang.reflect.Method.invoke(Method.java:511)
07-29 14:49:47.463: W/System.err(2745): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-29 14:49:47.485: W/System.err(2745): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-29 14:49:47.493: W/System.err(2745): at dalvik.system.NativeStart.main(Native Method)
I am not able to capture breakpoint on callback method. plz help if you have gone through this error.
below is my code for getting user details:
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
//RFR//_("onSessionStateChange----------------");
/////////////// super.onSessionStateChange(state, exception);
if (state.isOpened()) {
readUserInfo(session);
} else if (state.isClosed()) {
// Session closed
}
}
private Request.GraphUserCallback graphCallback = new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
String name = user.getName();
String gender = (String) user.getProperty("gender");
String email = (String) user.getProperty("email");
String birthday = user.getBirthday();
Log.d("FB----->","name: "+ name +" gender: "+ gender +" email: "+ email +" birthday: " +birthday);
}
};
public void readUserInfo(Session session){
// make request to the /me API
Request.executeMeRequestAsync(session, graphCallback);
}
And below is the permission that I've set:
openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location"));
Here is the response i get from the graph api, when checked from browser:
{
"id": "1000000XXXXX930",
"name": "First Last",
"first_name": "First",
"last_name": "Last",
"link": "http://www.facebook.com/<myusername>",
"username": "<myusername>",
"gender": "male",
"locale": "en_US"
}
Exception is thrown because You are trying to access email
But user has not used email for registration and has used phone
number for the registration.
You have to check the possibility in code that whether the son
response has the key and only then try to extract the value of that
key
if(object.has("email")){
userEmail = object.getString("email");
}
Have you given "email" permission to request the Facebook application to access any user's email id?
If you want to access email id of Facebook user using API then you must need to give email permission. General info about user profile will not give you the email address of the Facebook user.
Email Permissions in Facebook API
NOTE: Some user also put security to do not share any email address to any other then also it might be the case that you will not get the email address.
Hope it will help you.
you do need permission to grab someone's email although some people have their privacy set so that you can get their emails without this expressed permission, most don't.
This Piece of code is working fine with me in getting required permissions
this will also help you in getting Email permission
private void FaceBookSignIn()
{
facebookBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(SignIn_Rewards.this, false, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
fromFB=true;
UserID=user.getId();
firstName=user.getFirstName();
Lastname=user.getLastName();
Gender=user.getProperty("gender").toString();
Email=user.getProperty("email").toString();
DateofBirth=user.getBirthday();
try {
getToken();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
}
});
}
// Do whatever u want. User has logged in
else if (!currentSession.isOpened()) {
// Ask for username and password
OpenRequest op = new Session.OpenRequest((Activity) context);
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
op.setCallback(null);
List<String> permissions = new ArrayList<String>();
permissions.add("publish_stream");
permissions.add("user_likes");
permissions.add("email");
permissions.add("user_birthday");
op.setPermissions(permissions);
Session session = new Session.Builder(SignIn_Rewards.this).build();
Session.setActiveSession(session);
session.openForPublish(op);
}
}
}) ;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
fromFB=true;
UserID=user.getId();
firstName=user.getFirstName();
Lastname=user.getLastName();
Gender=user.getProperty("gender").toString();
Email=user.getProperty("email").toString();
DateofBirth=user.getBirthday();
try {
getToken();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
}
});
}
}
You have check like this:
private Request.GraphUserCallback graphCallback = new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
String name = user.getName();
String gender = (String) user.getProperty("gender");
String email = (String) user.getProperty("email");
String birthday = user.getBirthday();
if(email!=null){
//perform your task here.
}else{
Log.v("email","is empty");
}
Log.d("FB----->","name: "+ name +" gender: "+ gender +" email: "+ email +" birthday: " +birthday);
}};
Try this to get value for email
Edited: By default you won't get the email, for email you have to specify permission.
Session.StatusCallback statusCallback = new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
if(session.isOpened())
{
Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if(user != null)
{
try
{
System.out.println("Graph Inner Json"+user.getInnerJSONObject());
String email = user.getInnerJSONObject().getString("email");
}
}
}
}
}
}
YourActivityName.openActiveSession(this, true, statusCallback);
This is our openActiveSession() where we specify permissions
private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback statusCallback)
{
OpenRequest openRequest = new OpenRequest(activity);
openRequest.setPermissions(Arrays.asList("user_birthday", "email"));
openRequest.setCallback(statusCallback);
Session session = new Session.Builder(activity).build();
if(SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI)
{
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
And in the End you should do in onActivityResult Method like:
if(Session.getActiveSession() != null)
{
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}

Android Facebook native app not getting user email and birthday even with permissions set and correct information in fields

I'm trying to get the user email and birthday (using a Me request). My app has email and user_birthday permissions and the fb account i'm using has an email and a birthday set.
When I try using the 'Graph API Explorer' (https://developers.facebook.com/tools/explorer) using the user access_token with 'fields=id,email,birthday' all I get is the id.
Can anybody advice me on this please.
Here is my code:
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request request = 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) {
// here I check the infos I got.
Log.d("some tag", user.getInnerJSONObject().toString()); // it shows only the id, no email or birthday.
if (Session.getActiveSession() != null) {
Log.i(TAG, "Log out from FB");
Session.getActiveSession().closeAndClearTokenInformation();
}
}
}
});
// set params.
request.getParameters().putString("fields", "id,email,birthday");
// execute request.
request.executeAsync();
Log.d(TAG, request.toString());
}
if (exception != null) {
exception.printStackTrace();
}
}
});
Many thanks.
I finally changed the approach using the OpenRequest instead of getMeRequest:
Here is my code:
public void onClick(View v) {
Logger.d(TAG, "Start FB session");
// check if a session exists.
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
// create a new session.
Session session = new Session.Builder(getApplicationContext()).build();
// set it a the active session.
Session.setActiveSession(session);
// keep a variable link to session.
currentSession = session;
}
// if a session is already open then issue a request using the available
// session. Otherwise ask for user credentials.
if (currentSession.isOpened()) {
// The user is logged in.
Logger.e(TAG, "User is logged in.");
Session.getActiveSession().closeAndClearTokenInformation();
Logger.i(TAG, "Session closed an token information cleared.");
// get user data here with no extra call.
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Logger.i(TAG, "User:" + user.getInnerJSONObject());
}
}
});
}
}
});
} else {
// Ask for username and password
OpenRequest op = new Session.OpenRequest((Activity) this);
// don't use SSO.
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
// no callback needed.
op.setCallback(null);
// set permissions.
List<String> permissions = new ArrayList<String>();
permissions.add("email");
permissions.add("user_birthday");
op.setPermissions(permissions);
// open session for read.
currentSession.openForRead(op);
Logger.d(TAG, "Session open for read request issued.");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Logger.d(TAG, "Request code is: " + requestCode);
Logger.d(TAG, "Result code is: " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(getApplicationContext()).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Logger.i(TAG, "User:" + user.getInnerJSONObject());
}
}
});
}
}
});
}
}
I hope this helps.
When you are using Request.GraphUserCallback(), its best to use it in MAIN UI THREAD
Session s = Session.getActiveSession();
if(s!=null)
{
Request.executeMeRequestAsync(s,new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if(user!=null)
{
try {
String fbid=null;
String birthday=null;
fbid=user.getId();
birthday=user.getBirthday();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
});
}
you can try this also before the Request.executeMeRequestAsync(...){...}
List<String> permissions = session.getPermissions();
List<String> permissionsBirthday = new ArrayList<String>();
permissionsBirthday.add("user_birthday");
if (!isSubsetOf(permissionsBirthday, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, permissionsBirthday);
if (setPermissions(session, newPermissionsRequest))
return;
}
the method isSubsetOf();
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
hope this helps.
This code worked for me hope you find it useful. This retrieves the user email in 3 different ways and also logs it
try{
// new Read().execute("Facebook");
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// TextView welcome = (TextView) findViewById(R.id.welcome);
// welcome.setText("Hello " + user.getName() + "!");
Log.d("useremai", (String) user.getProperty("email"));
Log.d("USER", user.getInnerJSONObject().toString());
JSONObject details = user.getInnerJSONObject();
useremail = details.optString("email");
Log.d("name", user.getName());
Log.d("email", useremail);
}
}
});
}
}
});
}catch(NoClassDefFoundError e){
e.printStackTrace();
}
Try this one:
if you have object of user than do below:
if (user != null) {
String UserId = user.getId();
try {
Log.i("Birthdate", ""+user.getInnerJSONObject().getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
}
}

Android facebook - login popup don't appear

I am just starting with facebook api so if my problem is easy to solve please don't hate me for asking.
I am working on an Android application that logs into FB. I have FB api set up like in tutorial on devFB.
Everything works nice, u press Login button and FB login screen appears as popup where u can log in etc.
But when on device there is a FBapp then my code redirects to this application for authorization and then just hang doing nothing, zero, null.
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
// make request to the /me API
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.instructionsOrLink);
welcome.setText("Hello "+ user.getName() + "!");
it is copy of tutorial code.
Any suggestions how to prevent this ?
I'm using this code, maybe you should try it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
emailAddress = user.getProperty("email").toString();
name = user.getName();
fbId = user.getId();
Communication.loginWithFb(FacebookLoginActivity.this, user.getId());
}
}
});
} else if (session.getState().equals(SessionState.CLOSED_LOGIN_FAILED)) {
Toast.makeText(FacebookLoginActivity.this, getResources().getString(R.string.login_with_facebook_error), Toast.LENGTH_LONG).show();
finish();
}
}
}, null);
}
private Session openActiveSession(Activity activity, boolean allowLoginUI, StatusCallback callback,
List<String> permissions) {
OpenRequest openRequest = new OpenRequest(activity).setPermissions(permissions).setCallback(callback);
Session session = new Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
public void onDataDownloaded(CommunicationOutput<UserData> output) {
...
}

Facebook SDK 3.0 Android - Token missing

I'm trying to use the facebook authentification in my app but I'm not able to login because the token is missing. In the LogCat I have a loop : "[Tag]System.out [Text]doLogin:".
This happens before the Facebook dialog, and when it appears I click on "Ok" but nothing happens.
Here is my code:
private SharedPreferences.Editor loginPrefsEditor;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fb_auth);
choosePseudoButton = (Button) findViewById(R.id.buttonChoosePseudoFb);
progressBarFb = (ProgressBar) findViewById(R.id.progressBarFbLoad);
textViewFbInfo = (TextView) findViewById(R.id.currentInfoFb);
editTextFbPseudo = (EditText) findViewById(R.id.editTextPseudoFb);
/*
* Get existing access_token if any
*/
mPrefs = getPreferences(MODE_PRIVATE);
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
System.out.println("onCreate");
fbToken = session.getAccessToken();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", fbToken);
JSONRequest jr = (JSONRequest) new JSONRequest().execute();
}
}
});
}
else {
doLogin();
}
}
});
}
private void doLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
fbToken = session.getAccessToken();
System.out.println("doLogin: "+fbToken);
JSONRequest jr = (JSONRequest) new JSONRequest().execute();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
fbToken = session.getAccessToken();
System.out.println("updateView: "+fbToken);
JSONRequest jr = (JSONRequest) new JSONRequest().execute();
}
else {
doLogin();
}
}
private class SessionStatusCallback implements Session.StatusCallback {
public void call(Session session, SessionState state, Exception exception) {
// Respond to session state changes, ex: updating the view
if( session.isOpened() ){
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
}
});
}
updateView();
}
}
Several things to note:
Session opening happens asynchronously, meaning that when you call Session.openActiveSession, it does not (always) immediately open the session (it has to call into another activity, wait for user input, etc). So your line
fbToken = session.getAccessToken();
will almost always return null.
Secondly, there are a few states a Session can be in before it gets to the OPENED state, so in your SessionStatusCallback, you should probably move the updateView() call to be inside the if(session.isOpened()) check.
Lastly, you're calling Session.openActiveSession in the onCreate method, and in that callback, you're always calling doLogin() if the session is not opened. But like I said before, the session can transition to multiple states before it's OPENED, so you're in fact calling doLogin multiple times. Remove that doLogin() call.

Categories

Resources