Android FacebookSDK get Birthday - android

I have created sample app with facebook sdk integration. Now I can Login with facebook Also get some basic information from facebook. But fail to got birthday from "GraphUser" I have noticed that for birthday I need to set permission "user_birthday" which I have already set. I couldn't get what wrong with response.
private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback callback, List 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() {
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();
Log.d("AllData", user.toString());
Log.e("facebookId", id);
Log.e("firstName", firstName);
Log.e("lastName", lastName);
Log.e("email", email);
String Birthdate=user.getBirthday();
Log.e("Birthdate", Birthdate+"::Birthdate");
}
}
}).executeAsync();
}
}
}, Arrays.asList(
new String[] { "email", "user_location", "user_birthday","user_likes" }));
}
GraphUser respose is
GraphObject{graphObjectClass=GraphUser, state={"id":"…..","first_name":"…..","timezone":5.5,"email":"…..#gmail.com","verified":false,"name":"…..","locale":"en_US","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/....\/","last_name":"…..","gender":"male","updated_time":"2012-12-21T06:54:19+0000"}}

Are you trying this with an admin/tester/developer user of your Facebook app? If not, the reason is that if you request extended permissions, you'll need to get your app through the Facebook app review process, as described here:
https://developers.facebook.com/docs/apps/review/login#do-you-need-review

Related

Why Facebook Session state is always close?

I want to add Facebook login functionality into my app. Please note that:
I don't want to use Facebook login button widget.
I copy pasted my code that was working correctly last year (from my other project) into my new project.
I checked Session page and I guess I have no problem.
The only difference was Request.executeMeRequestAsync() hss changed to Request.newMeRequest(). I did this change but seems my session is always close although I could see Session.setActiveSession(session); method runs by debug of project. So, have no idea really why session is always close in call() method.
Any idea would be appreciated. Thanks.
My code:
public class FacebookLogin extends FragmentActivity
{
private static final String TAG = "FacebookLogin";
private static final List<String> READ_PERMISSIONS =
Arrays.asList("email", "user_about_me", "user_photos");
// private static final List<String> WRITE_PERMISSIONS = Arrays.asList("");
private final Session.StatusCallback statusCallback = new Session.StatusCallback()
{
#Override
public void call(final 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)
{
MyLog.d(TAG, "User name: " + user.getName() + "!, Login successfully :)");
MyLog.d(TAG, "User id: " + user.getId());
MyLog.d(TAG, "Access token is: " + session.getAccessToken());
MyLog.d(TAG, "Application id: " + session.getApplicationId());
MyLog.d(TAG, "JSON Object: " + user.getInnerJSONObject());
SpStorage.setKeyFacebook(FacebookLogin.this, session.getAccessToken());
SpStorage.setFacebookUserId(FacebookLogin.this, user.getId());
// erson person = parseJSON(user.getInnerJSONObject().toString());
// registerUser();
// Close activity
FacebookLogin.this.finish();
}
}
});
request.executeAsync();
}
else if (state.isClosed()) {
MyLog.d(TAG, "Facebook session closed");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Find device hash key (should not be used in production)
// printHashKey();
// start Facebook Login
openActiveSession(this, true, statusCallback, READ_PERMISSIONS);
}
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;
}
}
What I get in logcat:
Facebook session closed
You need to override the onActivityResult method in your Fragment class and pass it on to the session in order to complete the session transitions.
This needs to happen regardless of whether you're using the UiLifecycleHelper or not.
You need to override onActivityResult and pass the values to the facebook SDK.
From Facebook's SDK docs:
To ensure that the sessions are set up correctly, your fragment must
override the fragment lifecycle methods: onCreate(), onResume(),
onPause(), onDestroy(), onActivityResult() and onSaveInstanceState()
and call the corresponding UiLifecycleHelper methods. For example,
calling the onCreate() method in the UiLifecycleHelper object creates
the Facebook session and opens it automatically if a cached token is
available.
Recently Facebook is using API V2.2 and it has deleted some methods.
recently Before 1 week i have done some for getting user information.
Which may be helping you.
public void getProfileData(View button){
Session activeSession = Session.getActiveSession();
new Request(
activeSession,
"me",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
try
{ GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
String name23 = jso.getString("name");
Log.e("Name response",""+name23);
name = name23;
Toast.makeText(getApplicationContext(), "Name: " + name , Toast.LENGTH_LONG).show();
}
catch ( Throwable t )
{
t.printStackTrace();
}
String name = response.toString();
Log.e("Name request",""+name);
}
}
).executeAsync();
}

how to get email id from facebook sdk in android applications?

I integrated Facebook login in my android application. I want to get email id of login user. How will I get it?
private void loginToFacebook() {
Session.openActiveSession(this, true, 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, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
userID =user.getId();
provider="facebook";
userName=user.getUsername();
firstName=user.getFirstName();
lastName=user.getLastName();
Log.d("****User****", "details:" + user);
}catch(Exception e){
Here is my code. i use Request.GraphUserCallback() method but there is no response of email from this method.
Before calling Session.openActiveSession do this to get permissions add this:
List<String> permissions = new ArrayList<String>();
permissions.add("email");
The last parameter in Session.openActiveSession() should be permissions.
Now you can access user.getProperty("email").toString().
EDIT:
This is the way I am doing facebook authorization:
List<String> permissions = new ArrayList<String>();
permissions.add("email");
loginProgress.setVisibility(View.VISIBLE);
//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.executeMeRequestAsync(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();
Log.e("facebookid", id);
Log.e("firstName", firstName);
Log.e("lastName", lastName);
Log.e("email", email);
}
}
});
}
}
}, permissions);
Add this method to your activity:
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;
}
Following the suggestion of Egor N, I change my old code
Session.openActiveSession(this, true, statusCallback);
whith this new one:
List<String> permissions = new ArrayList<String>();
permissions.add("email");
Session.openActiveSession(this, true, permissions, statusCallback);
Now FB ask the user about the permission of email and I can read it in the response.
Try this article. Hope your issues will be solved Click Here
Btw, You need to use user.asMap().get("email").toString()); for receving the User Email ID.
Also, you need to assign that into some of label like lblEmail.setText where lblEmail is a Textview.

Get Facebook friends list using openActiveSession or REST API

I'm developing an Android app with latest facebook SDK and I'm using this code to get some data from facebook:
public void onFBLoginClick(View view)
{
openActiveSession(this, true, statusCallback);
}
Session.StatusCallback statusCallback = 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)
{
txtUserName.setText(session.getAccessToken());
String gender = user.getProperty("gender").toString();
String email = user.getProperty("email").toString();
saveUserData(user.getId(), user.getName(), user.getBirthday(), user.asMap().get("email").toString());
saveAccessToken(session.getAccessToken());
getFacebookUserProfilePicture(session.getAccessToken());
}
}
});
}
}
};
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;
}
Using this code, how can I get friends list? Or, do I have to use REST API to do it?

Graph api is not returning user email id

In this code GraphUser is not returning email-id and contact number.
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
// userInfoTextView.setVisibility(View.VISIBLE);
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Display the parsed user info
String email= (String) response.getGraphObject().getProperty("email");
System.out.println("yahooooooooooo "+email);
buildUserInfoDisplay(user);
}
}
});
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
private String buildUserInfoDisplay(GraphUser user) {
StringBuilder userInfo = new StringBuilder("");
// Example: typed access (name)
// - no special permissions required
userInfo.append(String.format("Name: %s\n\n",
user.getName()));
// Example: typed access (birthday)
// - requires user_birthday permission
userInfo.append(String.format("Birthday: %s\n\n",
user.getBirthday()));
userInfo.append(String.format("Birthday: %s\n\n",
user.getBirthday()));
userInfo.append(String.format("Gender: %s\n\n",
user.getProperty("gender")));
userInfo.append(String.format("Iddddddd: %s\n\n",
user.getId()));
// Example: partially typed access, to location field,
// name key (location)
// - requires user_location permission
userInfo.append(String.format("Location: %s\n\n",
user.getLocation().getProperty("name")));
// Example: access via property name (locale)
// - no special permissions required
userInfo.append(String.format("Locale: %s\n\n",
user.getProperty("locale")));
return userInfo.toString();
}
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 inside onActivityResult() don't forget to do
if(Session.getActiveSession() != null)
{
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
I got another situation where i was passing all the permissions but still getting error "No value for email". The reason behind this was that there was no primary email verified for that Facebook account (To see Primary Email in Facebook go to Account Settings--> Email).
So if there is no primary Email is verified for a Facebook account then you will always get this error. Please be sure that there is one verified primary Email for that Facebook account you are accessing.

How to get the Facebook Friendlist using Intent in Android?

I would like to get the friendlist of the facebook using intent.
Please let me know if there is any way to get the friends list of the facebook by using built in application of the device.
Thanks.
You need to integrate the Android SDK into your app, here is the link to download the latest SDK. You then will have to have the user authenticate your app to access their information.
Here is sample code to do this
private SessionTracker mSessionTracker;
private Session mCurrentSession;
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(SignUpChoices.this);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
mCurrentSession.openForRead(openRequest);
Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject());
}
});
}
}
}
One you have a user that has approved your app you can perform other Request about their information. friends info example
Finally i found a way to get the friendlist of the Facebook using Intent.
Intent m_fb=getOpenFacebookIntent(m_context);
startActivity(m_fb);
public static Intent getOpenFacebookIntent(Context context) {
try {
context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
return new Intent(Intent.ACTION_VIEW,Uri.parse("fb://profile/<user_id>/fans"));
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/abc.xyz"));
}
}
You can use Official Facebook App with Intent listed HERE.

Categories

Resources