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

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

Related

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.

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

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

Android Facebook SDK birthday returns null

I am using Facebook SDK(facebook-android-sdk-3.16) and try to retrieve user public_profile information.
But when I am try to get User Birthday It always gives me null
Here It my code:
public void onClick(View view) {
openActiveSession(_mActivity, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.v(APP_TAG, " ============== " + session.getPermissions());
Log.v(APP_TAG, " ============== " + session.isPermissionGranted("user_birthday"));
//make request to the /me API);
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
Log.d(APP_TAG, " ============== " + response);
if (user != null) {
_medtFName.setText(user.getFirstName());
_medtLName.setText(user.getLastName());
_medtEmailAddress.setText(user.getProperty("email").toString());
Log.i(APP_TAG, " ============== " + user.getBirthday());
Log.i(APP_TAG, " ============== " + user.getProperty("gender").toString());
}
}
});
}
}
});
}
private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback callback) {
Session.Builder builder = new Builder(activity);
Session session = builder.build();
Session.OpenRequest openRequest = new OpenRequest(activity);
List<String> permission=new ArrayList<String>();
permission.add("user_birthday");
permission.add("user_likes");
permission.add("user_location");
permission.add("email");
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
openRequest.setPermissions(permission);
Session.setActiveSession(session);//This will take care of the null pointer
openRequest.setCallback(callback);//the callback
session.openForRead(openRequest);
return session;
}
return null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(_mActivity, requestCode, resultCode, data);
}
when I try to call session.isPermissionGranted("user_birthday") its gives false
How I get grated permission for user_birthday
You are getting null because you need your APK reviewed by Facebook to get user's birthday, if you will try to login with developer's Facebook account (from which facebook application have been created) you will get birthday but for general public access you have to provide APK for review to Facebook.
Let me know if you have any queries.
For birthday and Email address you can not get in first (Log in authentication ) call in this call you only gets user general profile only few parameters .
If you want to fetch date of Birth / E mail/ friend list so you have to make separate call post authentication with specific permission. For permission go through the following link
https://developers.facebook.com/docs/facebook-login/permissions

Graph User returning Null, even though the session is created

I have been trying to integrate facebook to my app, but it always returns a Null Graph user.I tried adding the onActivityResult method as a solution told here, but still doesn't seem to help.
public class FacebookRegistartionActivity extends FragmentActivity
{
private Session.StatusCallback mStatusCallback = new SessionStatusCallback();
// private static final int REQUEST_CODE_SIGN_IN = 1;
Session session;
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
fbRegistration();
}
public void fbRegistration() {
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
session = Session.getActiveSession();
Log.i("", "Session before : "+session);
if (session == null) {
session = new Session(FacebookRegistartionActivity.this);
if (session != null) {
Session.setActiveSession(session);
if (session != null && !session.isOpened()&& !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(mStatusCallback));
} else {
}
}
} else {
Log.i("", "Session null ... : "+session);
// start Facebook Login
Session.openActiveSession(this, true, mStatusCallback);
}
}
The code doesn't even reach the onActivityResult() method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Log.i("", "requestCode : "+requestCode);
Log.i("", "resultCode : "+resultCode);
Log.i("", "data : "+data);
if (resultCode == RESULT_OK) {
Session.getActiveSession().onActivityResult(this, requestCode,resultCode, data);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
Log.i("", "session in on status call back....."+session);
// Here the session is there, not null
if (session.isOpened()) {
Log.i("", "session is opened....."+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(final GraphUser user, Response response) {
Log.i("in SignUp", "USER :: " + user);
// Log.i("in SignUp", "response :: " + response);
if (user != null) {
try{
String fqlQuery = "select url from profile_pic where id=me() and width=200 and height=200";
Bundle params1 = new Bundle();
params1.putString("q", fqlQuery);
Session session = Session.getActiveSession();
Request request = new Request(session, "/fql", params1,
HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try {
String serverresponse=response.getGraphObject().getInnerJSONObject().toString();
Log.e("serverresponse", ""+serverresponse);
JSONObject jsonobj=new JSONObject(serverresponse);
JSONArray array=jsonobj.getJSONArray("data");
Log.e("","data object : "+array);
jsonobj = array.getJSONObject(0);
String fbUserImageUrl = jsonobj.getString("url");
Log.e("","image url : "+fbUserImageUrl);
Logger.show(Log.INFO, "", " AccessToken with publish stream:: " +Session.getActiveSession().getAccessToken());
String uniqueId = user.getId();
String userName = user.getName();
String image = fbUserImageUrl; //"http://graph.facebook.com/"+user.getId()+"/picture?type=large";
String emailId = user.asMap().get("email").toString();
Logger.show(Log.INFO,"","uniqueId :: "+ uniqueId);
Logger.show(Log.INFO,"","userName :: "+ userName);
Logger.show(Log.INFO,"","image :: "+ image);
Logger.show(Log.INFO,"","emailId :: "+ emailId);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
Request.executeBatchAsync(request);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
else
{
Log.i("", "Graph user null");
// Always the Graph user is returning Null
}
}
}).executeAsync();
}
else
{
Log.i("", "Session not opened still.....");
}
}
}
}
EDIT :
I checked for answers, then realized, I just missed to add the permissions into the Android Manifest file.
Just realized! I Did everything except adding the following permission in Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
But, Still wonder how I was able to get the session. Means, it does not require a net connection? Taken in to account that the device I tested had the facebook app installed in it.
Is the session provided by the facebook app, instead? Wished to know how the facebook app works in the login flow in our app, using the facebook sdk.
Any help regarding this is appreciated.
As I have mentioned in comment - Yes it is true that when a facebook Session object is created, it attempts to initialize itself from a TokenCachingStrategy. But there must be a Session token cache. As you have told that you were using same app id from some other app, the app was authorized by the user and the session was created and saved in the cache.
Because facebook manages session based on the app id and as the session was already created it fetched it from cache for your new app. But for fetching graph user when you call Request.newMeRequest, it is making an internet connection, since the internet permission was not there in the manifest, your app was not able to connect to facebook server to fetch the same.

Facebook SDK email sometimes returns null - 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);
}
}

Categories

Resources