Hi. I want add facebook sdk to my app for authorization/login. I register my app, testing - all work, until I add permission (for email), and now I cath NullPointerException - code:
private void startFacebookLogin() {
Session.StatusCallback mCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// 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) {
Log.d("FACEBOOK", "onCompleted()");
final GraphUser graphUser = user;
if (user != null) {
final Intent intent = new Intent(RegisterActivity.this, AboutYourselfActivity.class);
intent.putExtra(NAME, graphUser.getName());
intent.putExtra(EMAIL, (String) graphUser.asMap().get(EMAIL));
intent.putExtra(USER_SOCIAL_ID, graphUser.getId());
intent.putExtra(PROVIDER, FACEBOOK);
intent.putExtra(PASSWORD, "");
intent.putExtra(PHONE, "");
Log.d("FACEBOOK USER ", graphUser.getName());
Log.d("FACEBOOK USER ", graphUser.getId());
Log.d("FACEBOOK USER ",(String) graphUser.asMap().get(EMAIL));
RegisterActivity.this.startActivity(intent);
//RegisterActivity.this.finish();
URL img_value = null;
try {
img_value = new URL("http://graph.facebook.com/" + user.getId() + "/picture?type=small");
BitmapLoaderTask task = new BitmapLoaderTask(new DownloadComplete() {
#Override
public void complete() {
}
});
task.execute(img_value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
} else {
Log.d("FACEBOOK", "hmm " + session.getState().toString());
}
}
};
Session.OpenRequest request = new Session.OpenRequest(RegisterActivity.this);
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(RegisterActivity.this);
}
mFacebookSession.openForRead(request);
}
Here i have crash
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data); // here I cath crash
}
}
Logs:
FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {com.DriverNotes.AndroidMobileClientTest/com.DriverNotes.AndroidMobileClientTest.RegisterActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3406)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3449)
at android.app.ActivityThread.access$1200(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1328)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.DriverNotes.AndroidMobileClientTest.RegisterActivity.onActivityResult(RegisterActivity.java:300)
at android.app.Activity.dispatchActivityResult(Activity.java:5456)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3402)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3449)
at android.app.ActivityThread.access$1200(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1328)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
try this
private void performFacebookLogin()
{
Log.d("FACEBOOK", "performFacebookLogin");
final Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, Arrays.asList("email"));
Session openActiveSession = Session.openActiveSession(this, true, new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
Log.d("FACEBOOK", "call");
if (session.isOpened() && !isFetching)
{
Log.d("FACEBOOK", "if (session.isOpened() && !isFetching)");
isFetching = true;
session.requestNewReadPermissions(newPermissionsRequest);
Request getMe = Request.newMeRequest(session, new GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
Log.d("FACEBOOK", "onCompleted");
if (user != null)
{
Log.d("FACEBOOK", "user != null");
org.json.JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String email = graphResponse.optString("email");
String id = graphResponse.optString("id");
//String facebookName = user.getUsername();
System.out.println("Birthday--------------"+user.getBirthday());
System.out.println("User ID----------------"+user.getId());
System.out.println("LINK---------------------"+user.getLink());
System.out.println("username---------------"+user.getUsername());
System.out.println("Hashcode----------------"+user.hashCode());
System.out.println("Inner JSON--------------"+user.getInnerJSONObject());
System.out.println("Location-------------------"+user.getLocation());
System.out.println("class------------------------"+user.getClass());
System.out.println(user.getProperty("email"));
if (email == null || email.length() < 0)
{
System.out.println(
"Facebook Login"+
"An email address is required for your account, we could" +
" not find an email associated with this Facebook account. Please associate a email with this account or login the oldskool way.");
return;
}
}
}
});
getMe.executeAsync();
}
else
{
if (!session.isOpened())
Log.d("FACEBOOK", "!session.isOpened()");
else
Log.d("FACEBOOK", "isFetching");
}
}
});
}
Try this:
List<String> permissions = Arrays.asList("public_profile", "user_birthday", "email");
Session session = Session.openActiveSession(this, false, permissions, statusCallback);
if(session == null) {
session = Session.openActiveSession(this, true, permissions, statusCallback);
Session.setActiveSession(session);
//Log.e("session2 ", "session " + session.getAccessToken());
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest((Activity) v.getContext()).setCallback(statusCallback));
}
}
else
{
//DO WHATEVER YOU HAVE TO DO Session.getActiveSession().getAccessToken() should exist
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
// Respond to session state changes, ex: updating the view
Log.e("session", "session " + session.getAccessToken() + " state: " + state.isOpened());
}
}
Sorry, create a public instance variable:
private Session.StatusCallback statusCallback = new SessionStatusCallback();
I used this code and now authorization is worked
List<String> permissions = new ArrayList<String>();
permissions.add("email");
permissions.add("user_photos");
//start Facebook 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
Log.e("sessionOpened", "true");
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Work with user (get name, email and other)
}
}
}).executeAsync();
}
}
}, permissions);
Thank you men for help. Now all work, code:
private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback callback, List<String> permissions) {
Session.OpenRequest openRequest = new Session.OpenRequest(activity).setPermissions(permissions).setCallback(callback);
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;
}
private void startFacebookLogin() {
List<String> permissions = new ArrayList<String>();
permissions.add("email");
//start Facebook 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
Log.e("sessionOpened", "true");
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
String firstName = user.getFirstName();
String lastName = user.getLastName();
String id = user.getId();
String email = user.getProperty("email").toString();
final Intent intent = new Intent(RegisterActivity.this, AboutYourselfActivity.class);
intent.putExtra(NAME, user.getName());
intent.putExtra(EMAIL, user.getProperty("email").toString());
intent.putExtra(USER_SOCIAL_ID,user.getId());
intent.putExtra(PROVIDER, FACEBOOK);
intent.putExtra(PASSWORD, "");
intent.putExtra(PHONE, "");
DatabaseManager.getInstance(RegisterActivity.this).
setProperty(FACEBOOK_USER_NAME, user.getName());
DatabaseManager.getInstance(RegisterActivity.this).
setProperty(FACEBOOK_USER_EMAIL, user.getProperty("email").toString());
DatabaseManager.getInstance(RegisterActivity.this).
setProperty(FACEBOOK_USER_ID, user.getId());
Log.e("facebookId", id);
Log.e("firstName", firstName);
Log.e("lastName", lastName);
Log.e("email", email);
}
}
}).executeAsync();
}
}
}, permissions);
Related
I am building an android application where I am using facebook login. The code work very fine when there is facebook application installed in my phone.
Now the problem is that when there is no facebook application installed in my phone then the app crush on retrieving the mail ID.
Here is my fb login code -
onCreateView -
loginBtn.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
// getting name of the user
name = user.getName();
// getting email of the user
email = user
.getProperty("email")
.toString();
// getting gender of the user
id = user.getId();
URL image_value = null;
try {
image_value = new URL("https://graph.facebook.com/" + id + "/picture");
} catch (MalformedURLException e) {
e.printStackTrace();
}
profile_pic_url = image_value.toString();
Intent gps = new Intent(getApplicationContext(), GPS.class);
// store string value
editor.putString("fblogout", "1"); // Storing string
editor.putString("name", name); // Storing string
editor.putString("mail_id", email);
editor.putString("id", id);
editor.putString("profile_pic_url", profile_pic_url);
editor.commit();
startActivity(gps);
} else {
}
}
});
onSession Open -
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
buttonsEnabled(true);
} else if (state.isClosed()) {
buttonsEnabled(false);
}
}
};
public boolean checkPermissions() {
Session s = Session.getActiveSession();
if (s != null) {
return s.getPermissions().contains("publish_actions");
} else
return false;
}
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
Error log -
at com.facebook.Request$1.onCompleted(Request.java:283)
at com.facebook.Request$4.run(Request.java:1668)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5034)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
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 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);
}
}
});
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);
}
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();
}
}