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();
}
});
Related
I am new for facebook sdk.
Does any know how to get firstname, lastname, email, id, birthday, gender, hometown, age and etc from facebook sdk in android platform?
Please show me the code?
below is what I have tried
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions( "public_profile", "email", "user_birthday", "user_friends");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
try {
if (object != null) {
JSONObject obj = response.getJSONObject();
id = obj.getString("id");
name = obj.getString("name");
birthday = obj.getString("birthday");
email = obj.getString("email");
String gender = obj.getString("gender");
showUserInfoToast();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
I tried but it does not work....
please help
Please try this code .Hope it will fetch all the data you needed.Thanx
public void onSuccess(final LoginResult loginResult) {
Log.e("bug", "facebook sign in success");
if (loginResult != null) {
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
firstName = profile.getFirstName();
lastName = profile.getLastName();
social_id = profile.getId();
profileURL = String.valueOf(profile.getProfilePictureUri(200, 200));
Log.e(TAG, "social Id: " + profileURL);
}
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e("bug", "facebook social_id=>" + social_id + " toeken" + loginResult.getAccessToken().getToken());
Log.e("bug", "graph response=>" + object.toString());
try {
if (object.has("name")) {
String[] name = object.getString("name").split(" ");
firstName = name[0];
lastName = name[1];
}
email = object.has("email") ? object.getString("email") : "";
social_id = object.has("id") ? object.getString("id") : "";
socialSignUp("facebook");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,name,last_name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
The data you access depends on the permissions someone grants your app and data they chose to share with apps (Link)
These fields can be null
To get any user-specific data other than userId, nameand email you have to submit your app for review to facebook console so that facebook will have clarity that what you want to do with user personal data.
If it is some sort of useful thing your app is doing with this data then facebook will allow you to access that data like birthday date, user_friends and user gender.
To do that go to facebook developer console and follow there procedure.
Hope this will help you to achieve what you want to achieve.
I'm using the FB Sdk to let a user login through FB but on clicking the Continue with Facebook button the screen is getting stuck at Loading... Below is the screenshot.
This is the code I'm using https://stackoverflow.com/a/29379794
What could be the reason that the screen is stuck at Loading?
Use this below code for Facebook Login :
login.setLoginBehavior(LoginBehavior.WEB_ONLY);
login.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e("ACESS_ON_SUCCESS---", "" + loginResult.getAccessToken());
token = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e("ACESS_ON_COMPLETED--", "" + AccessToken.getCurrentAccessToken());
Log.e("FaceBook Response", response.toString());
String responseStr = response.toString();
sharedpreferences = App.getInstance().getDefaultAppSharedPreferences();
editor = sharedpreferences.edit();
try {
if (responseStr.contains("\"id\"")) {
id = object.getString("id");
Log.e("USER-ID = ", id);
editor.putString(SharedPreferencesConstants.facebookId,id);
}
if (responseStr.contains("\"name\"")) {
name = object.getString("name");
Log.e("NAME = ", name);
editor.putString(SharedPreferencesConstants.userName,name);
}
if (responseStr.contains("\"email\"")) {
email = object.getString("email");
Log.e("EMAIL = ", email);
editor.putString(SharedPreferencesConstants.userEmail,email); }
if (responseStr.contains("\"birthday\"")) {
birthday = object.getString("birthday");
Log.e("BIRTHDAY = ", birthday);
editor.putString(SharedPreferencesConstants.userFbBirthday,birthday);
String strYear = birthday.substring(6, 10);
Log.e("BIRTHDAY LEN", strYear);
editor.putString(SharedPreferencesConstants.userFbBirthdayYear,strYear);
}
//EXTRACT PICTUREOBJECT FROM MAINJSONOBJECT::::---
if (responseStr.contains("\"picture\"")) {
JSONObject pictureObject = object.getJSONObject("picture");
Log.e("PICTUREOBJ FRM MAINOBJ", "" + pictureObject.toString());
//EXTRACT DATAOBJECT FROM PICTUREOBJECT::::---
JSONObject dataObject = pictureObject.getJSONObject("data");
//EXTRACT PROFILE_PIC FROM DATAOBJECT::::---
profile_pic = dataObject.getString("url");
Bundle params = new Bundle();
parameters.putString("limit", total_friends_count);
request1.setParameters(params);
request1.executeAsync();*/
}
#Override
public void onCancel() {
Log.e("Error","canceled");
}
#Override
public void onError(FacebookException error) {
Log.e("Error",error.getMessage());
Toast.makeText(WelcomeActivity.this, "FB Integration Failed", Toast.LENGTH_SHORT).show();
}
});
}
I have been having this issue for a bit now and I can't seem to find the solution. I have tried the graph API as well as the Profile tracker. Both seems to be giving issues. The Graph API lets the application crash with a null object reference for the users ID and when using the profile tracker, the application doesn't continue beyond that part.
Here is my code with the tracker commented out and the graph API being used.
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
/*if(Profile.getCurrentProfile() == null) {
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
// profile2 is the new profile
Mint.leaveBreadcrumb("Login Activity ~ Waiting for facebook to return profile");
Log.v("facebook - profile", profile2.getFirstName());
profileTracker.stopTracking();
}
};
// no need to call startTracking() on mProfileTracker
// because it is called by its constructor, internally.
}
else {
Profile profile = Profile.getCurrentProfile();
Mint.leaveBreadcrumb("Login Activity ~ Current Profile" + profile);
Mint.leaveBreadcrumb("Login Activity ~ Current FBID" + profile.getId());
SetUserData();
LogIn();
///
continueToAdverts();
}*/
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
//String name = object.getString("name");
//String email = object.getString("email");
//String id = object.getString("id");
//Toast.makeText(MainActivity.this, name + " " + " " + email + " " + id, Toast.LENGTH_SHORT).show();
AppGlobal.LoggedUser = new UserInfo();
AppGlobal.LoggedUser.setFacebookId(object.getString("id"));
SetUserData();
LogIn();
///
continueToAdverts();
} catch (JSONException ex) {
ex.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
Am I missing something?
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 email address which I know depends if the user has provided one on his account. Now the account I'm using to test provides one for sure but for unknown reason the facebook SDK only provides the user_id and the fullname of the account and nothing else. 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 email as all the answers I've seen so far doesn't provide the email on my end. Here's my code so far:
Login Button
#OnClick(R.id.btn_login)
public void loginFacebook(){
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
}
LoginManager Callback:
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
requestUserProfile(loginResult);
}
#Override
public void onCancel() {
Toast.makeText(getBaseContext(),"Login Cancelled", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
Toast.makeText(getBaseContext(),"Problem connecting to Facebook", Toast.LENGTH_SHORT).show();
}
});
And the request for user profile:
public void requestUserProfile(LoginResult loginResult){
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
try {
String email = response.getJSONObject().get("email").toString();
Log.e("Result", email);
} catch (JSONException e) {
e.printStackTrace();
}
String id = me.optString("id");
// send email and id to your web server
Log.e("Result1", response.getRawResponse());
Log.e("Result", me.toString());
}
}
}).executeAsync();
}
The JSON response returns only the ID and full name of my account but doesn't include the email. Did I missed out something?
You need to ask for parameters to facebook in order to get your data. Here I post my function where I get the facebook data. The key is in this line:
parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // ParĂ¡metros que pedimos a facebook
btnLoginFb.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Procesando datos...");
progressDialog.show();
String accessToken = loginResult.getAccessToken().getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.i("LoginActivity", response.toString());
// Get facebook data from login
Bundle bFacebookData = getFacebookData(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // ParĂ¡metros que pedimos a facebook
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
private Bundle getFacebookData(JSONObject object) {
try {
Bundle bundle = new Bundle();
String id = object.getString("id");
try {
URL profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=150");
Log.i("profile_pic", profile_pic + "");
bundle.putString("profile_pic", profile_pic.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
bundle.putString("idFacebook", id);
if (object.has("first_name"))
bundle.putString("first_name", object.getString("first_name"));
if (object.has("last_name"))
bundle.putString("last_name", object.getString("last_name"));
if (object.has("email"))
bundle.putString("email", object.getString("email"));
if (object.has("gender"))
bundle.putString("gender", object.getString("gender"));
if (object.has("birthday"))
bundle.putString("birthday", object.getString("birthday"));
if (object.has("location"))
bundle.putString("location", object.getJSONObject("location").getString("name"));
return bundle;
}
catch(JSONException e) {
Log.d(TAG,"Error parsing JSON");
}
return null;
}
Instead of getting the value of the graphResponse, access the email using the JSONObject me
userEmail = jsonObject.getString("email");
Hope it helps you
/*** setupFacebook stuff like make login with facebook and get the userId,Name and Email*/
private void setupFacebookStuff() {
Log.e(TAG, "key hash= " + Utils.getKeyHash(SplashActivity.this, getPackageName()));
// This should normally be on your application class
FacebookSdk.sdkInitialize(SplashActivity.this);
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
currentAccessToken.getToken();
}
};
loginManager = LoginManager.getInstance();
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
preference.setUserLogin(true);
final GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Log.e("id", "" + object);
if (object.has(getString(R.string.fbParamId))) {
final String userId = object.optString(getString(R.string.fbParamId));
final String userPicture = "https://graph.facebook.com/" + object.optString(getString(R.string.fbParamId)) + "/picture?type=large";
preference.setUserId(userId);
preference.setUserPictureUrl(userPicture);
}
if (object.has(getString(R.string.fbParamUserName))) {
final String userName = object.optString(getString(R.string.fbParamUserName));
preference.setUserName(userName);
}
if (object.has(getString(R.string.fbParamEmail))) {
final String userEmail = object.optString(getString(R.string.fbParamEmail));
preference.setUserName(userEmail);
Log.e("useremail", userEmail);
}
callMainActivity(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
final Bundle parameters = new Bundle();
parameters.putString("fields", "name,email,id");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Toast.makeText(getBaseContext(), "Login Cancelled", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getBaseContext(), "Problem connecting to Facebook", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Facebook login error " + error);
}
});
}
You can also use GraphResponse object to get the values
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
try {
// Application code
String email = response.getJSONObject().getString("email");
txtStatus.setText("Login Success \n" + email);
}catch(Exception e){
e.printStackTrace();;
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel()
{
txtStatus.setText("==============Login Cancelled=============");
}
#Override
public void onError(FacebookException exception)
{
txtStatus.setText("==============Login Error=================");
exception.printStackTrace();
}
});
Putting this code:
btnLoginFb.setReadPermissions(Arrays.asList("email"));
before
RegisterCallback
should solve the problem.
I guess getting email permissions can help..
LoginManager.getInstance().logInWithReadPermissions(
fragmentOrActivity,
Arrays.asList("email"));
Information
If you are giving any permission to get an email address.
then, Facebook can not every time gives you email address or some other details.
When, Facebook user is not signup with his email-address then Facebook can't provide you his email address.
If user is login with Facebook using email address then Facebook will provides email to you.
Facebook SDK provide only public details.
check a login with Facebook using email-address and also with phone number through.
My application allows the user to connect with Facebook. I want to get userprofile information after login with Facebook (using Facebook SDK 4.0.1). I think that I should use aynctask to get it but I don't know how.
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
System.out.println("onSuccess");
msginfo.setText("You can now share image on facebook");
otherview.setVisibility(View.VISIBLE);
GraphRequest request = GraphRequest.newMeRequest
(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted(JSONObject object, GraphResponse response)
{
// Application code
Log.v("LoginActivity", response.toString());
//System.out.println("Check: " + response.toString());
try
{
String id = object.getString("id");
idT.setText(object.getString("id"));
ppv.setProfileId(object.getString("id"));
nameT.setText(object.getString("name"));
emailT.setText(object.getString("email"));
locationT.setText(object.getString("address"));
String name = object.getString("name");
String email = object.getString("email");
String gender = object.getString("gender");
String birthday = object.getString("birthday");
// String location = object.getString("location");
// String location = object.getString("user_location");
// String location = object.getString("address");
System.out.println(id + ", " + name + ", " + email + ", " + gender + ", " + birthday);
// locationT.setText(location);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday,link");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel()
{
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception)
{
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
And I can get the profile informations in the current activity but not in the next one.
I think you are missing permissions
parameters.putString("fields", "id,name,email,gender,picture,birthday");
And then you can easily get profile pic
object.getJSONObject("picture").getJSONObject("data").getString("url");
Hope it helps.