Facebook SDK email sometimes returns null - Android - android

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);
}
}

Related

How to get Facebook user gender , email, phone number details

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

Fb not providing Login info to users that are not listed in app's role as admin or tester

I have a confusable situation here. In my android app, I am using Fb login and SDK.Things work fine when fb native app is not present.But when fb app is there and login is done then FB provides info only when I logged on with native FB app and not when somebody else logins. The screen just flashes once and goes away. I have also found that roles that are listed in app on fb including me (admin) & testers are able to fetch information, but not the other normal users. I have tried but I dont know where the fault is happening?
thanks.
public void signInWithFacebook() {
Constant.printKeyHash(MainActivity.this);
mSessionTracker = new SessionTracker(mContext, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
}
}, null, false);
String applicationId = Utility.getMetadataApplicationId(mContext);
Constant.mCurrentSession = mSessionTracker.getSession();
if (Constant.mCurrentSession == null || Constant.mCurrentSession.getState().isClosed()) {
mSessionTracker.setSession(null);
Session session = new Session.Builder(mContext).setApplicationId(applicationId).build();
Session.setActiveSession(session);
Constant.mCurrentSession = session;
} else {
mSessionTracker.setSession(null);
Session session = new Session.Builder(mContext).setApplicationId(applicationId).build();
Session.setActiveSession(session);
Constant.mCurrentSession = session;
}
if (!Constant.mCurrentSession.isOpened()) {
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest((Activity) mContext);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location", "user_friends"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
Constant.mCurrentSession.openForRead(openRequest);
try {
// progressfb.show();
// progressfb.setCancelable(false);
}
catch (Exception e)
{
}
accessFacebookUserInfo();
}
} else {
// progressfb.show();
accessFacebookUserInfo();
}
}
public void accessFacebookUserInfo() {
if (Session.getActiveSession() != null || Session.getActiveSession().isOpened()) {
Bundle bundle = new Bundle();
bundle.putString("fields", "picture,email,first_name, last_name, name");
// bundle.putString("fields", "email");
// bundle.putString("fields", "first_name");
final Request request = new Request(Session.getActiveSession(), "me", bundle, HttpMethod.GET, new Request.Callback() {
#SuppressWarnings("unused")
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
if (graphObject != null) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject = graphObject.getInnerJSONObject();
Log.i("", "faacebook response===" + jsonObject.toString());
String facebook_id = jsonObject.getString("id");
JSONObject picture_obj = jsonObject.getJSONObject("picture");
JSONObject picture_data = picture_obj.getJSONObject("data");
// fb_pic_url = picture_data.getString("url");
String first_name = jsonObject.getString("name");
String last_name = jsonObject.getString("last_name");
String socialName = jsonObject.getString("name");
eemail = jsonObject.getString("email");
String fb_pic_url = "https://graph.facebook.com/"
+ facebook_id
+ "/picture?type=large";
new fbSigninActivity().execute(eemail,first_name);
callFacebookLogout(MainActivity.this);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mContext, "something went wrong", Toast.LENGTH_LONG).show();
}
}
}
});
Request.executeBatchAsync(request);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// com.facebook.Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
if (Constant.mCurrentSession.isOpened()) {
accessFacebookUserInfo();
} else {
//Utils.showCenterToast(contxt, getResources().getString(R.string.msg_went_wrong));
}
} else {
Constant.mCurrentSession = null;
mSessionTracker.setSession(null);
// progressfb.dismiss();
}
}
The issue is happening because the feature you are trying to use needs to be approved by Facebook first. You must submit an APK for them to test. Anyone listed as an Admin, Developer, or Tester of your app should work fine (you may need to add their debug hash of the device to the list). But until your app gets approved by Facebook to use specific features or Graph Calls normal users will NOT be able to use it.

NullPointerException by ActivityResult, Facebook sdk

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);

Get Facebook User's Email address

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);
}
}
});

Android: Getting Friends Birthday Using Graph API Facebook SDK 3.0 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: How to get friends birth dates from facebook calendar using Graph API
Refer to: https://stackoverflow.com/a/13926065/1770916
I set permissions for getting friends birthday and list. code is below.
private void signInWithFacebook() {
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(MainActivity.this);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location", "friends_birthday","read_friendlists" ));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
mCurrentSession.openForRead(openRequest);
}
}
}
But I am getting only Friend ID and Name only.
#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() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
Log.d("AL", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject());
}
});
Request.executeMyFriendsRequestAsync(mCurrentSession, new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
Log.d("AL",""+response.toString());
for (int i=0;i<users.size();i++){
Log.d("AL",""+users.get(i).toString());
welcome.setText("Done");
}
}
});
}
}
By using above code i am getting users additional things like email, birthday etc after adding permissions but not getting friends additional thinks like birthday.
where i am doing wrong???
For Getting Friends Information we need to get HttpConnection for following url
"https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture,birthday");
Here add Fields which you require.
I think it will work ..
Here we get any thing for this
String url = "https://graph.facebook.com/me/friends?fields=birthday,name&access_token="+ facebook.getAccessToken();
using this iam getting birthdays
JSONObject JOAlbums = JAAlbums.getJSONObject(i);
String date = DaysCount(JOAlbums.getString("birthday"));

Categories

Resources