This is what i am doing to get user detail. I am able to get FbId,user name and usergender,I wants to get user birthdate too.please check below code Thanks in advance :-
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse response) {
// Application code
if (AccessToken.getCurrentAccessToken() != null) {
if (user != null) {
Log4Android.e(FaceBookLogin.this, user.toString());
// Log.e("onCompleted ", " 1= > " + new Gson().toJson(user));
facebookUser = new Gson().fromJson(user.toString(), FacebookUser.class);
try {
// Log.e("onCompleted ", " 2= > " + new Gson().toJson(user));
Log.e("onCompleted ", " 22= > " + new Gson().toJson(facebookUser));
if (facebookUser.getEmail() != null || !facebookUser.getEmail().equals("")) {
checkUserStatus(context, facebookUser.getId());
} else {
UtilitySingleton.getInstance(context).ShowToast(R.string.email_error);
}
} catch (Exception e) {
e.printStackTrace();
facebookUser = getUsableData(response);
UtilitySingleton.getInstance(context).ShowToast(R.string.email_error);
}
}
}
}
});
Bundle parameters = new Bundle();
// parameters.putString("fields", "id,name,email,first_name,last_name");
parameters.putString("fields", "id,name,email,gender,birthday,first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
What permissions are you asking for?
getting the user birthday requires the permission: "user_birthday".
This solved my proplem:-
String BIRTHDATE = "user_birthday";
public static final String[] FACEBOOK_PERMISSIONS = {ValueKeys.PUBLIC_PROFILE, ValueKeys.EMAIL, BIRTHDATE};
LoginManager.getInstance().logInWithReadPermissions((Activity) context, Arrays.asList(FACEBOOK_PERMISSIONS));
In order to get the permission go to your facebook dashboard >App review > start a submission > and select user_birthday
You can do something along these lines of code -
if (AccessToken.getCurrentAccessToken() != null) {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse response) {
if (response != null && response.getJSONObject() != null) {
try {
String birthDate = response.getJSONObject().getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields","id,name,email,gender,birthday,first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
}
And you should always check for access token before sending a GraphRequest.
Related
I'm currently creating a test application to test using the latest facebook SDK to update our existing application problem is that I need to get the user birthday. I'm confused on this since the the SDK3 and above provides more information than the updated SDK4 and I'm lost on how to get the birthday as all the answers I've seen so far doesn't provide the birthday on my end. Here's my code so far:
LoginButton CallBacks:
fbLogin = (LoginButton) findViewById(R.id.login_button);
fbLogin.setReadPermissions(Arrays.asList("email", "user_birthday"));
fbLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
if (object.has("id"))
id = object.getString("id");
if (object.has("name"))
userName = object.getString("name");
if (object.has("email"))
userEmail = object.getString("email");
if (object.has("gender"))
gender = object.getString("gender");
if (object.has("birthday"))
birthday = object.getString("birthday");
String profile_URL = "https://graph.facebook.com/" + id+ "/picture?type=large";
LogCat.show(id + "\n" + userName + "\n" + userEmail + "\n" + birthday + "\n" + profile_URL + "\n" + gender);
} catch (Exception e) {
e.printStackTrace();
LogCat.show("Error:" + e.getMessage());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Toast.makeText(SplashLogin.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException exception) {
// App code
Toast.makeText(SplashLogin.this, "" + exception.toString(), Toast.LENGTH_SHORT).show();
}
});
The JSON response returns only the ID and name, email and gender of my account but doesn't include the birthday. Did I missed out something?
According to the latest sdk of facebook, to get birthday you need to first submit your application for review. On test applications you can just get the public profile which includes the following things
id
cover
name
first_name
last_name
age_range
link
gender
locale
picture
timezone
updated_time
verified
For more information you can read the following documentation from this link
If your app requests this permission Facebook will have to review how
your app uses it. link
Facebook don't give user birthday by default.You have to use extended permissions.
I solve this problem by enable permission of Birthday in my app from the Facebook Developer Console.
fbSignUp.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Data.fbAccessToken = loginResult.getAccessToken().getToken();
LogCat.show(loginResult.getAccessToken().getToken());
if (object.has("id")) {
id = object.getString("id");
Data.fbId = object.getString("id");
}
if (object.has("name")) {
userName = object.getString("name");
;
Data.fbUserName = object.getString("name");
}
if (object.has("email")) {
userEmail = object.getString("email");
Data.fbUserEmail = object.getString("email");
}
if (object.has("birthday")) {
userBirthDay = object.getString("birthday");
}
else {
if (userEmail == null || "".equalsIgnoreCase(userEmail)) {
if (userName != null && !"".equalsIgnoreCase(userName)) {
userEmail = userName + "#facebook.com";
Data.fbUserEmail = Data.fbUserName + "#facebook.com";
} else {
userEmail = id + "#facebook.com";
Data.fbUserEmail = Data.fbId + "#facebook.com";
}
}
}
} catch (Exception e) {
e.printStackTrace();
LogCat.show("Error:" + e.getMessage());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,birthday,gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Toast.makeText(RegisterScreen.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException exception) {
// App code
Toast.makeText(RegisterScreen.this, "" + exception.toString(), Toast.LENGTH_SHORT).show();
}
});
I am using ParseFacebook SDK for my android application. I have used parse sdk code from there website, some of the code snippets are given below, it is successfully login with facebook, but i can't be able to extract my facebook information like: MyProfileImage, Username etc.
In Application Class:
ParseFacebookUtils.initialize(this);
In my class where i am using Facebook Login:
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignInActivity.this, Arrays.asList("email", "user_photos", "public_profile", "user_friends"), new LogInCallback() {
#Override
public void done(ParseUser user, com.parse.ParseException e) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
}
);
Please help me out here to extract the information for username and profile image. Thanks in adavance
This is what works for me
public static void FaceBookLogin(final Activity context){
ArrayList permissions=new ArrayList<String>();
//permissions.add("publish_stream");
permissions.add("user_likes");
permissions.add("email");
permissions.add("user_birthday");
ParseFacebookUtils.logInWithReadPermissionsInBackground(context, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Toast.makeText(context,"You have cancelled to connect via facebook",Toast.LENGTH_SHORT);
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Toast.makeText(context,"You have successfully connected via facebook",Toast.LENGTH_SHORT);
Log.d("MyApp", "User signed up and logged in through Facebook!");
try {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
// Application code
if (response.getError() != null) {
System.out.println("ERROR");
} else {
System.out.println("Success");
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
String fbUserId = json.optString("id");
String fbUserFirstName = json.optString("name");
String fbUserEmail = json.optString("email");
String fbUserProfilePics = "http://graph.facebook.com/" + fbUserId + "/picture?type=large";
ParseUser.getCurrentUser().setEmail(fbUserEmail);
ParseUser.getCurrentUser().put("First_Name",fbUserFirstName);
ParseUser.getCurrentUser().put("FaceBookUrl",fbUserProfilePics);
ParseUser.getCurrentUser().saveInBackground();
}
Log.v("FaceBook Response :", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT);
}
if (ParseUser.getCurrentUser().getBoolean("IsTermsAccepted")==true){
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}else{
Utils.ShowTermsofUse(context);
}
} else {
Toast.makeText(context,"You have successfully connected via facebook",Toast.LENGTH_SHORT);
Log.d("MyApp", "User logged in through Facebook!");
try {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
// Application code
if (response.getError() != null) {
System.out.println("ERROR");
} else {
System.out.println("Success");
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
String fbUserId = json.optString("id");
String fbUserFirstName = json.optString("name");
String fbUserEmail = json.optString("email");
String fbUserProfilePics = "http://graph.facebook.com/" + fbUserId + "/picture?type=large";
ParseUser.getCurrentUser().setEmail(fbUserEmail);
ParseUser.getCurrentUser().put("First_Name",fbUserFirstName);
ParseUser.getCurrentUser().put("FaceBookUrl",fbUserProfilePics);
ParseUser.getCurrentUser().saveInBackground();
}
Log.v("FaceBook Response :", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT);
}
if (ParseUser.getCurrentUser().getBoolean("IsTermsAccepted")==true){
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}else{
Utils.ShowTermsofUse(context);
}
}
Toast.makeText(context,err.getMessage(),Toast.LENGTH_SHORT);
}
}) ;
}
And dont forget to call onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
case FACEBOOK:
ParseFacebookUtils.onActivityResult(FACEBOOK, resultCode, data);
break;
}
Hope this helps
I am trying to perform a Facebook Checkin from an Android app that I am developing. I know we have to use the graph API. But I am not sure what all are required to get it working. Is there an example code for this?
I reviewed this link: Publishing checkins on facebook through android app
How do I use this code? Any help on this is appreciated.
public class FBCheckin extends Fragment implements View.OnClickListener {
Button checkin;
public String pageID;
String FACEBOOK_LINK = "https://www.facebook.com/pizzaguydelivery";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View rootview = inflater.inflate(R.layout.fblogin, container, false);
checkin.setOnClickListener(this);
return rootview;
}
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithPublishPermissions(getActivity(), Arrays.asList("publish_actions"));
pageID = FACEBOOK_LINK.substring(FACEBOOK_LINK.lastIndexOf("/") + 1, FACEBOOK_LINK.length());
new GraphRequest(AccessToken.getCurrentAccessToken(), "/" + pageID, null, HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
if (response.getError() == null) {
JSONObject obj = response.getJSONObject();
if (obj.has("id")) {
pageID = obj.getString("id");
Bundle params = new Bundle();
params.putString("message", "Eating");
params.putString("place", pageID);
// params.putString("link", "URL");
if (pageID == null) {
//Toast.makeText(getApplicationContext(),"Failed to check in",Toast.LENGTH_SHORT).show();
} else {
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/feed", params, HttpMethod.POST, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
if (response.getError() == null) {
//success
} else {
//Toast.makeText(getApplicationContext(),"Failed to check in",Toast.LENGTH_SHORT).show();
}
}
}).executeAsync();
}
}
}
} catch (JSONException q) {
// TODO Auto-generated catch block
//Toast.makeText(getApplicationContext(),q.getMessage(),Toast.LENGTH_SHORT).show();
q.printStackTrace();
}
}
}).executeAsync();
}
}
The following code only checks in to locations with facebook pages via pageid. ( Like restaurants.) But think you can do it with place id too.
LoginManager.getInstance().logInWithPublishPermissions(
getActivity(), Arrays.asList("publish_actions"));
String PAGEID = FACEBOOK_LINK.substring(
FACEBOOK_LINK.lastIndexOf("/") + 1,
FACEBOOK_LINK.length());
new GraphRequest(AccessToken.getCurrentAccessToken(), "/"
+ PAGEID, null, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
if (response.getError() == null) {
JSONObject obj = response
.getJSONObject();
if (obj.has("id")) {
pageID = obj.getString("id");
/* make the API call */
Bundle params = new Bundle();
params.putString("message", "Eating");
params.putString("place", pageID);
params.putString("link","URL");
if (pageID == null) {
MessageBox
.Show(getActivity(),
"Failed to check in to this restaurant");
} else {
new GraphRequest(AccessToken
.getCurrentAccessToken(),
"/me/feed", params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(
GraphResponse response) {
if (response.getError() == null) {
//success
} else {
MessageBox
.Show(getActivity(),
"Failed to check in to this restaurant");
}
}
}).executeAsync();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
MessageBox.Show(getActivity(),
"Error: " + e.getMessage());
e.printStackTrace();
}
}
}
}).executeAsync();
I know this code is a bit messy but it get the work done. Here the first thing that I am doing is asking user for facebook publish permission. Then I check if the pageID that I am checking into is valid through a graph request. If it is valid then I am checking in the user to his desired location through another request.
Currently, I am using this tutorial to create the facebook login.
"https://github.com/ParsePlatform/ParseUI-Android"
The Parse user JSON didn't return me an email or gender. I also have research around but I still can't find the solution (well, at least, some other still returning null). Anyone can explain the reason and how to solve it?
facebookLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loadingStart(false); // Facebook login pop-up already has a spinner
if (config.isFacebookLoginNeedPublishPermissions()) {
ParseFacebookUtils.logInWithPublishPermissionsInBackground(getActivity(),
Arrays.asList(
"public_profile", "email"), facebookLoginCallbackV4);
Log.i("fbUser","Publish");
} else {
ParseFacebookUtils.logInWithReadPermissionsInBackground(getActivity(),
Arrays.asList( "public_profile", "email"), facebookLoginCallbackV4);
Log.i("fbUser", "Read");
}
}
});
private LogInCallback facebookLoginCallbackV4 = new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (isActivityDestroyed()) {
return;
}
if (user == null) {
loadingFinish();
if (e != null) {
showToast(R.string.com_parse_ui_facebook_login_failed_toast);
debugLog(getString(R.string.com_parse_ui_login_warning_facebook_login_failed) +
e.toString());
}
} else if (user.isNew()) {
GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject fbUser,
GraphResponse response) {
/*
If we were able to successfully retrieve the Facebook
user's name, let's set it on the fullName field.
*/
ParseUser parseUser = ParseUser.getCurrentUser();
if (fbUser != null && parseUser != null && fbUser.optString("name").length() > 0) {
Log.i("FbUSer", response.getJSONObject().toString());
Log.d("FbUSer-Email",fbUser.optString("email"));
Log.i("FbUSer-gender",fbUser.optString("gender"));
parseUser.put(USER_OBJECT_NAME_FIELD, fbUser.optString("name"));
parseUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
debugLog(getString(
R.string.com_parse_ui_login_warning_facebook_login_user_update_failed) +
e.toString());
}
loginSuccess();
}
});
}
loginSuccess();
}
}
).executeAsync();
} else {
loginSuccess();
}
}
};
Logcat Section return:
{"id":"1234524124124","name":"FbUser NAme"}
I just found the answer. I just need to set the parameter so I can get the data I want.
GraphRequest request = GraphRequest.newMeRequest(...);
Bundle parameters = new Bundle();
parameters.putString("fields","id,name,link,email,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
Reference: https://stackoverflow.com/a/32579366/4961962
for more user info you have to add permissoin to access those detail like email, user_about_me at facebook developer console
select app at facebook developer and go -> app details -> Configure
App Center Permissions
Facebook have change API to 4.0
and how can I get user mail address
because new class is called profile can't get that.
It might callback from graph API?
private void GraphAPIprofile() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
Log.i("Graph API", response.toString());
Log.i("User Mail", object.optString("email"));
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
I think there have something wrong with me..
please help, thanks
Try this code:-
if (Session.getActiveSession() == null
|| Session.getActiveSession().isClosed()) {
Session.openActiveSession(this, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
System.out.println("State= " + state);
if (session.isOpened()) {
System.out.println("Token=" + session.getAccessToken());
Request.executeMeRequestAsync(session,
new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
System.out.println("User=" + user);
}
if (response != null) {
System.out.println("Response="
+ response);
Toast.makeText(FBConnect.this,
response.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
if (exception != null) {
System.out.println("Some thing bad happened!");
exception.printStackTrace();
}
}
});
}
Write this code in onResume of your activity or wherever you want to access user's data.