I am working on Facebook integration in my application:
But something going wrong and the email address of the user always returns null value:
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
..
..
//initiate session
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
Session.OpenRequest op = new Session.OpenRequest(this);
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.setActiveSession(session);
session.openForPublish(op);
}
}
}
#Override
public void onStart() {
Logger.d(TAG,"onStart");
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
Logger.d(TAG,"onStop");
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Logger.d(TAG,"onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Logger.d(TAG,"onSaveInstanceState");
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void getUserDetails(Session session) {
Logger.d(TAG,"getUserDetails");
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
Log.d(TAG,"newMeRequest:onCompleted");
if (user != null) {
fbCurrentUser = user;
Log.d(TAG,"Already logged-in : "+ user.getId());
Log.d(TAG,"User First Name: "+ user.getFirstName());
Log.d(TAG, "User Email: " + user.getProperty("email"));
Log.e(TAG, "response: " + response);
Log.e(TAG, "user: " + user.toString());
//check if new user [get his friends list]
getFriendsList();
} else {
Log.e(TAG,"No User Found");
}
}
});
Request.executeBatchAsync(request);
}
Please Help!
Thanks in advance!
Check the response giving any error or not then
JSONObject json = com.facebook.android.Util.parseJson(response);
if(json != null){
final String id = json.getString("id");
final String email = json.getString("email");
}
Try this for getting email,
String email = user.asMap().get("email").toString();
Log.d(TAG, "User Email: " + email);
TextView mEmail = (TextView) findViewById(R.id.textView1);
mEmail.setText(email);
or else give a try to below code
Log.d(TAG, "User Email: " + user.getProperty("email").toString());
just add toString() at end of Log for more reference check this link
With this above piece of code i am successfully able to get the user's email.
Edit
Session.openActiveSession(this, true, new Session.StatusCallback() {
#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() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
String email = user.asMap()
.get("email").toString();
mEmail.setText(email);
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Error...",
Toast.LENGTH_LONG);
}
}
});
Related
public class FacebookLoginActivity extends ActionBarActivity {
private List<String> permissions = new ArrayList<String>();
// FaceBook
private Session.StatusCallback statusCallback = new SessionStatusCallback();
private Button facebook_sigin;
private TextView name, email, gender, phone, address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb);
name = (TextView) findViewById(R.id.textView1);
gender = (TextView) findViewById(R.id.gender);
phone = (TextView) findViewById(R.id.phone);
address = (TextView) findViewById(R.id.address);
facebook_sigin = (Button) findViewById(R.id.facebooksigin);
permissions.add("email");
permissions.add("gender");
permissions.add("address");
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
facebook_sigin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (UtillClass.isConnectingToInternet(FacebookLoginActivity.this)) {
Session session = Session.getActiveSession();
if (session != null && !session.isOpened()
&& !session.isClosed()) {
Log.e("facebook login", "1");
Session.OpenRequest request = new Session.OpenRequest(
FacebookLoginActivity.this);
request.setPermissions(permissions);
request.setCallback(statusCallback);
session.openForRead(request);
} else {
Log.e("facebook login", "2");
Session.openActiveSession(FacebookLoginActivity.this, true,
statusCallback);
}
}
}
});
Session session = Session.getActiveSession();
if (session == null) {
if (session == null) {
session = new Session(this);
session.openForRead(new Session.OpenRequest(this).setPermissions(Arrays.asList("email")));
}
Session.setActiveSession(session);
}
}
public class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(final Session session, SessionState state,
Exception exception) {
Request request = new Request(session, "/me", null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
Log.e("Facebook Response ", "Response==>"+response);
Log.e("Facebook Login ", "onCompleted");
Log.e("session", "" + session.getAccessToken());
try {
JSONObject userDetails = response
.getGraphObject().getInnerJSONObject();
Log.e("fblogijsnresponse",userDetails.toString());
Log.e("facebook user id=",
userDetails.getString("id"));
if (userDetails.has("name")) {
Log.e("facebook user name=",
userDetails.getString("name"));
name.setText(userDetails.getString("name"));
}
if (userDetails.has("first_name")) {
Log.e("fbuserfname=", userDetails.getString("first_name"));
}
if (userDetails.has("last_name")) {
Log.e("fbuserlname=",userDetails.getString("last_name"));
}
if (userDetails.has("gender")) {
Log.e("fbgender","fbgender");
Log.e("fbgender=",userDetails.getString("gender"));
gender.setText(userDetails.getString("gender"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
request.executeAsync();
}
}
#Override
public void onStart() {
super.onStart();
Log.e("facebook", "onStart");
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
super.onStop();
Log.e("facebook", "onStop");
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e("facebook", "onSaveInstanceState");
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#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 onBackPressed() {
super.onBackPressed();
// goBack();
}
}
I tried to get facebook user gender ,email, phone and address detail. Can any please help me to find out those details. The above code i have added the permissions for gender , email, address but in facebook response have only facebook user name. I didn't whether we can get all details are not please help me solve this.
Please define permission in that manner.
your_fb_button.setReadPermissions("user_friends");
your_fb_button.setReadPermissions("public_profile");
your_fb_button.setReadPermissions("email");
your_fb_button.setReadPermissions("user_birthday");
for more details please follow this example: Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User
I'm able to get all those things as shown in my code below, but unable to retrieve email from the user profile.
What can I do for this?
Any kind of help will be appreciated.
Earlier I was using this source to get details of Facebook user and was fetching data (including Email) without any trouble:
public class MainActivity extends Activity {
private Session.StatusCallback sessionStatusCallback;
private Session currentSession;
private Button login;
private Button logout;
private Button publishButton;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
// create instace for sessionStatusCallback
sessionStatusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
connectToFB();
}
});
logout = (Button) findViewById(R.id.logoutButton);
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (currentSession != null) {
currentSession.closeAndClearTokenInformation();
...
}
}
});
// publish button
publishButton = (Button) findViewById(R.id.publishButton);
publishButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
}
public void connectToFB() {
List<String> permissions = new ArrayList<String>();
permissions.add("publish_actions");
currentSession = new Session.Builder(this).build();
currentSession.addCallback(sessionStatusCallback);
Session.OpenRequest openRequest = new Session.OpenRequest(
MainActivity.this);
openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
openRequest.setPermissions(permissions);
currentSession.openForPublish(openRequest);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (currentSession != null) {
currentSession
.onActivityResult(this, requestCode, resultCode, data);
}
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (session != currentSession) {
return;
}
if (state.isOpened()) {
// Log in just happened.
Toast.makeText(getApplicationContext(), "session opened",
Toast.LENGTH_SHORT).show();
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
String fbId = user.getId();
String fbName = user.getName();
String gender = user.asMap().get("gender").toString();
String email = user.asMap().get("email").toString();
String first = user.asMap().get("first_name").toString();
String last = user.asMap().get("last_name").toString();
textView.setText("Id: " + fbId + ", Name: " + fbName + ", Gender: " + gender + ", EmailID: " + email + ", First: " + first + ", Last: " + last);
}
});
} else if (state.isClosed()) {
// Log out just happened. Update the UI.
Toast.makeText(getApplicationContext(), "session closed",
Toast.LENGTH_SHORT).show();
}
}
public void publishStory() {
....
}
}
And now I am using same code in one of my project, but always getting:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at c.o.m.MainActivity$5.onCompleted(MainActivity.java:262)
at com.facebook.Request$1.onCompleted(Request.java:303)
at com.facebook.Request$4.run(Request.java:1726)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
At this line, I am getting NPE:
String email = user.asMap().get("email").toString();
Code:
public class MainActivity extends Activity {
Button btnFBLogin, btnGPLogin;
private Session.StatusCallback sessionStatusCallback;
private Session currentSession;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_layout);
sessionStatusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
btnFBLogin = (Button) findViewById(R.id.loginFB);
btnFBLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
connectToFB();
}
});
}
public void connectToFB() {
List<String> permissions = new ArrayList<String>();
permissions.add("publish_actions");
currentSession = new Session.Builder(this).build();
currentSession.addCallback(sessionStatusCallback);
Session.OpenRequest openRequest = new Session.OpenRequest(
MainActivity.this);
openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
openRequest.setPermissions(permissions);
currentSession.openForPublish(openRequest);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (currentSession != null) {
currentSession
.onActivityResult(this, requestCode, resultCode, data);
}
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (session != currentSession) {
return;
}
if (state.isOpened()) {
// Log in just happened.
Toast.makeText(getApplicationContext(), "session opened",
Toast.LENGTH_SHORT).show();
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
String fbId = user.getId();
String fbName = user.getName();
String gender = user.asMap().get("gender").toString();
String email = user.asMap().get("email").toString();
String first = user.asMap().get("first_name").toString();
String last = user.asMap().get("last_name").toString();
Toast.makeText(MainActivity.this, "EmailId:- "+email, Toast.LENGTH_LONG).show();
}
});
} else if (state.isClosed()) {
// Log out just happened. Update the UI.
Toast.makeText(getApplicationContext(), "session closed",
Toast.LENGTH_SHORT).show();
}
}
}
What could be the reason? Why its happening?
Sometime it might be happen that User not set their Email Id in their Profile which are you getting in Your Facebook Login Via Android so that throws Error like Null Pointer Exception.
So You should have to check before using the Email Variable after fetching from Login that it is null or not Such as :
String email ="";
if(user.asMap().get("email") != null){
email = user.asMap().get("email").toString();
}
You need to add "email" to the list of permissions you're requiring, otherwise the email will always be null. I don't know what version of the sdk you're using. With the last one you can write:
Collection<String> mPermissions = new ArrayList<>();
mPermissions.add("email");
LoginManager mLoginManager = LoginManager.getInstance();
CallbackManager mCallbackManager = CallbackManager.Factory.create();
FbCallback fbCallback = new FbCallback(this);
mLoginManager.registerCallback(mCallbackManager, fbCallback);
[...]
mLoginManager.logInWithReadPermissions(this, mPermissions);
By the way...remember that the user can revoke the permission or cannot grant it during the login.
i use facebook sdk to login to my app
i need only the accesstoken & email
when i click LoginButton (com.facebook.widget)
nothing nothing happens
when Debug - fail on session.isOpened();H
onCreate code:
lblEmail = (TextView) findViewById(R.id.lblEmail);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
authButton.setOnErrorListener(new LoginButton.OnErrorListener() {
#Override
public void onError(FacebookException error) {
Log.i(TAG, "Error " + error.getMessage());
}
});
// set permission list, Don't foeget to add email
authButton.setReadPermissions(Arrays.asList("basic_info", "email"));
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.i(TAG,"Access Token"+ session.getAccessToken());
//Request.executeMeRequestAsync(session,
Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Log.i(TAG, "User ID " + user.getId());
Log.i(TAG, "Email " + user.asMap().get("email"));
lblEmail.setText(user.asMap().get("email").toString());
}
}
}
);
}
}
});
try this for get facebook name,emailId and accessToken
Session session;
inside onCreate method
this.session = createSession();
this.session = Session.getActiveSession();
createSession method
private Session createSession() {
Session activeSession = Session.getActiveSession();
if (activeSession == null || activeSession.getState().isClosed()) {
activeSession = new Session.Builder(this).setApplicationId("APPLICATION-ID")
.build();
Session.setActiveSession(activeSession);
}
return activeSession;
}
login Button click
if (session.isOpened()) {
callRequest();
} else {
StatusCallback callback = new StatusCallback() {
public void call(Session session, SessionState state,
Exception exception) {
if (exception != null) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Login Failed")
.setMessage(exception.getMessage())
.setPositiveButton("OK", null).show();
session = createSession();
}
onSessionStateChange(session, state, exception);
}
};
session = createSession();
session.openForRead(new Session.OpenRequest(
MainActivity.this).setPermissions("email")
.setCallback(callback));
}
callRequest method
public void callRequest() {
if (!call) {
call = true;
Request.newMeRequest(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
try {
String name = user.getName();
String email = user.getProperty("email").toString();
String accessToken = session.getAccessToken();
System.out.println("name : " + name + "\nemail : "
+ email + "\naccessToken : " + accessToken);
Intent intent = new Intent(MainPageActivity.this,
HomeActivity.class);
intent.putExtra("u_name", name);
intent.putExtra("u_email", email);
intent.putExtra("accessToken", accessToken);
startActivity(intent);
overridePendingTransition(R.anim.slide_in,
R.anim.slide_out);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}).executeAsync();
}
}
onSessionStateChange method
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
callRequest();
}
}
onActivityResult method
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (this.session.onActivityResult(this, requestCode, resultCode, data)
&& this.session.getState().isOpened()) {
callRequest();
}
}
I'm having a problem when I'm trying to get the user's email from Android Facebook SDK. I have set the correct permissions and it works in some cases (I can get all data from user), but sometimes and in some devices, it doesn't work. Also I have disabled the sandbox mode and I have registed my certificate on facebook's site. Please, can anyone help me? Thank you!!!!
private void signInWithFacebook() {
SessionTracker mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
}
}, null, false);
String applicationId = Utility.getMetadataApplicationId(getBaseContext());
mCurrentSession = mSessionTracker.getSession();
if (mCurrentSession == null || mCurrentSession.getState().isClosed()) {
mSessionTracker.setSession(null);
Session session = new Session.Builder(getBaseContext()).setApplicationId(applicationId).build();
Session.setActiveSession(session);
mCurrentSession = session;
}
if (!mCurrentSession.isOpened()) {
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest(Main.this);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
mCurrentSession.openForRead(openRequest);
}
}
else{
Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
if(!mCurrentSession.getPermissions().contains("email")){
id = user.getId();
lastname = user.getName();
firstname = user.getFirstName();
email = user.getProperty("email").toString();
image = "http://graph.facebook.com/" + user.getId() + "/picture?type=large";
link = user.getLink();
ages = user.getBirthday();
sex = user.getProperty("gender").toString();
new CheckUser().execute();
}
else{
Toast.makeText(getApplicationContext(), "No email", Toast.LENGTH_LONG).show();
}
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
if (mCurrentSession.isOpened()) {
Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
id = user.getId();
lastname = user.getName();
firstname = user.getFirstName();
email = user.getProperty("email").toString();
image = "http://graph.facebook.com/" + user.getId() + "/picture?type=large";
link = user.getLink();
ages = user.getBirthday();
sex = user.getProperty("gender").toString();
new CheckUser().execute();
}
});
} else {
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest(Main.this);
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
mCurrentSession.openForRead(openRequest);
}
}
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();
}
}