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
Related
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":
}
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.
I am just starting with facebook api so if my problem is easy to solve please don't hate me for asking.
I am working on an Android application that logs into FB. I have FB api set up like in tutorial on devFB.
Everything works nice, u press Login button and FB login screen appears as popup where u can log in etc.
But when on device there is a FBapp then my code redirects to this application for authorization and then just hang doing nothing, zero, null.
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
// make request to the /me API
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.instructionsOrLink);
welcome.setText("Hello "+ user.getName() + "!");
it is copy of tutorial code.
Any suggestions how to prevent this ?
I'm using this code, maybe you should try it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
emailAddress = user.getProperty("email").toString();
name = user.getName();
fbId = user.getId();
Communication.loginWithFb(FacebookLoginActivity.this, user.getId());
}
}
});
} else if (session.getState().equals(SessionState.CLOSED_LOGIN_FAILED)) {
Toast.makeText(FacebookLoginActivity.this, getResources().getString(R.string.login_with_facebook_error), Toast.LENGTH_LONG).show();
finish();
}
}
}, null);
}
private Session openActiveSession(Activity activity, boolean allowLoginUI, StatusCallback callback,
List<String> permissions) {
OpenRequest openRequest = new OpenRequest(activity).setPermissions(permissions).setCallback(callback);
Session session = new Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
public void onDataDownloaded(CommunicationOutput<UserData> output) {
...
}
I'm developing an application in which I'm using Facebook log in button from SDK. I'm able to get access_token of the user but I want userID too. I have tried almost everything but was not successful. I have used facebook tutorial for achieving that. Here is the link: Facebook Login Button
Please help me in getting userID from the same login button.
Any kind of help will be appreciated.
Use the getId method of FB Profile class( Facebook SDK 4.0).
Profile profile = Profile.getCurrentProfile();
System.out.println(profile.getFirstName());
System.out.println(profile.getId());
loginResult.getAccessToken().getUserId()
After successful login, you need to call following code. You can get the logged-in user details with id in response.
Session session = Session.getActiveSession();
Request request = Request.newGraphPathRequest(session, "me", null);
com.facebook.Response response = Request.executeAndWait(request)
You should be used new facebook sdk 3.0 and
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
if (Session.getActiveSession().isOpened()) {
// Request user data and show the results
Request.executeMeRequestAsync(Session.getActiveSession(), new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
if (user != null) {
// Display the parsed user info
Log.v(TAG, "Response : " + response);
Log.v(TAG, "UserID : " + user.getId());
Log.v(TAG, "User FirstName : " + user.getFirstName());
}
}
});
}
}
Based on answer from #Ketan Mehta (https://stackoverflow.com/a/17397931/624109) that uses a deprecated API, you should use the following code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
if (Session.getActiveSession().isOpened())
{
// Request user data and show the results
Request.newMeRequest(Session.getActiveSession(), new GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if (null != user)
{
// Display the parsed user info
Log.v(TAG, "Response : " + response);
Log.v(TAG, "UserID : " + user.getId());
Log.v(TAG, "User FirstName : " + user.getFirstName());
}
}
}).executeAsync();
}
}
As these all answers are for older SDK , for SDK 4.0 here is the code
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Profile profile = Profile.getCurrentProfile();
Log.d("facebook",profile.getId());
}
#Override
public void onCancel() {
// App code
Log.d("facebook","failed");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.d("facebook","failed");
}
});
i was searching for the same thing looks like the Session object is no more accessible so above is the new way to get user profile and user id.
The Facebook graph API lets you make calls that return JSON, which you can parse in Android with a JSONObject like this below code.
JSONObject me = new JSONObject(fb.request("me"));
String id = me.getString("id");
You can get the user ID with this code :
document.getElementById('status').innerHTML =
'Welcome ' + response.name + '!' + "<br />"+
'Your user ID is : ' + response.id;
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"));