I am not able to get the gender here in OnCompleted function
I am able to get other params like id,name,email
Currently app is in Dev mode
This was working yesterday.
Code:
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
try {
AccessToken token = AccessToken.getCurrentAccessToken();
String accessToken = token.getToken().toString();
String expiresAt = token.getExpires().toString();
String id = object.getString("id");
String gender = object.getString("gender");
} catch (JSONException e) {
e.printStackTrace();
System.out.println(e.toString());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email, gender, location, picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
In your https://developers.facebook.com/ account, under App Review section, click Start a Submission, select user_gender from LOGIN PERMISSIONS and go through submission steps.
After facebook will approve user_gender permission, you can use it.
Again in your developer account click Settings then Advanced and in Upgrade API Version
change the API version your app calls to v3.1 and using below code, you will get the gender of the user.
private void attemptToLogIn() {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_gender"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
makeGraphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
public void makeGraphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(
token, (object, response) -> {
try {
String gender = object.getString("gender");
} catch (JSONException e) {
e.printStackTrace();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,gender");
request.setParameters(parameters);
request.executeAsync();
}
Your access token need the user_gender permission:
https://developers.facebook.com/docs/facebook-login/permissions/v3.0#reference-user_gender
Related
I am using the graph API. I used below code for getting email id. But email id is returning as empty. Email-id is verified and is able to login with the testing account. Did I make any mistake? Permissions have been accepted.
login(){
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("DEBUG",loginResult.getRecentlyDeniedPermissions()+" ACCEPTED PERMISSIONS :" +loginResult.getRecentlyGrantedPermissions());
Log.v("DEBUG",response.toString());
try {
String email = object.getString("id");
String name = object.getString("name");
LoginManager.getInstance().logOut();
sessionLogin(email, name, "Facebook");
} catch (JSONException e) {
Log.e(TAG, "facebook onCompleted exception: ", e);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,name,last_name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
In Android I wonder how to get a Facebook user id number after he has signed in to my app. I tried this:
com.facebook.Profile.getCurrentProfile().getId()
But for some reason that give me a number but it´s not the user id.
When I go to sites like https://findmyfbid.com/ I get the correct id like "23982739223233". Even when I right click my Facebook profile picture in web browser and copy link the "referrer_profile_id=23982739223233" in the link is correct.
But when I sign in using that Facebook this Profile.getCurrentProfile().getId() gives me a completely different number
You can use GraphRequest
in code:
List<String> permissionNeeds = Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends");
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.v("FACEBOOK LOGIN", response.toString());
String fb_id = object.getString("id"); //FaceBook User ID
String fb_name = object.getString("name");
String fb_email = object.getString("email");
String profilePicUrl = "https://graph.facebook.com/" + fb_id + "/picture?width=200&height=200";
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
Log.d("FACEBOOK ERRROR", "cancelled");
}
#Override
public void onError(FacebookException exception) {
Log.d("FACEBOOK ERRROR", exception.toString());
}
});
In Graph Request Response you can get user's Facebook Id, name , picture and other relevant information
ok I found the Answer. Looks like there is no common id for a Facebook user but my app get assigned a unique id as soon as user accept my app. Also here
This id is what i see with
com.facebook.Profile.getCurrentProfile().getId()
I'm trying to build a simple login to facebook app (with FB api v4.0)and retrieve some data about the user, but for some reason I success to login and get data only from my personal facebook profile, if tried to login with other users profile I'm getting null. (I change the setting in facebook developer to public app).
this is some of my loginButton_Fragment:
private CallbackManager callbackManager;
private FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
Log.d("koko",accessToken.toString() );
if (profile != null){
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
user_birthDay = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,birthday");
request.setParameters(parameters);
request.executeAsync();
user_name = profile.getName();
user_id = profile.getId();
Log.d("koko","first " +user_name + " " + user_id + " " + user_birthDay );
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
comm.respone(user_name, user_id, user_birthDay);
}
}, 500);
}
}
#Override
public void onCancel () {
}
#Override
public void onError (FacebookException e){
}
};
Each time I login, I'm getting inside the onSuccess, but if its not my personal profile so the profile its null.
set read permissions mButtonLogin.setReadPermissions(Arrays.asList("email,public_profile","user_birthday"));
try like this
mButtonLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("status", "onSuccess");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String name = object.getString("name");
String email =object.getString("email");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("status", "onCancel");
}
#Override
public void onError(FacebookException e) {
Log.d("status", "onError " + e);
}
}
);
You need to acquire app specific permission from Facebook for retrieve user personal information's such as birthday, user_friends etc by submitting it for a review.
Invest few moments here .
If your app requests such permissions Facebook will have to review how your app uses it.
You will get public_profile as it's default .
Check this & this .
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.
I have successfully installed the android sdk v4.0 in my studio.
I get to login correctly using LoginButton.
So far everything ok.
I want to have a string for each user data collecting interests me, for example:
String name = USER_NAME
String = USER_MAIL mail.
With the 3.0 sdk had it properly.
With the new SDK can not I do this, I followed the instructions in this thread:
Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User
I read in the documentation and in various threads about "Using the Graph API" but I can not get the data I'm looking for and assign them to each string.
this is my code (just as it is now):
LoginButton loginButton;
private CallbackManager mCallbackManager;
//...
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
mCallbackManager = CallbackManager.Factory.create();
//...
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Toast.makeText(Ready.this, "Connected!", Toast.LENGTH_SHORT).show();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
Log.v("LoginActivity", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v("LoginActivity", exception.getCause().toString());
}
});
As I said before, I connect with facebook perfectly, but do not know how to assign, for example, email to a string and name to another string.
Thank you very much in advance.
If you meant how to get name and email from the GraphRequest, it's simply this:
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String id=object.getString("id");
String name=object.getString("name");
String email=object.getString("email");
String gender=object.getString("gender");
String birthday=object.getString("birthday");
//do something with the data here
} catch (JSONException e) {
e.printStackTrace(); //something's seriously wrong here
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
GraphResponse contains things like the HTTPConnect used, any error encountered, etc. Assuming everything goes as expected, only JSONObject object is needed to retrieve the data requested.
My working code for getting the profile information
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
profile = Profile.getCurrentProfile();
if(profile != null){
fbUserId = profile.getId();
editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
editor.putString("FbId",profile.getId());
editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
editor.commit();
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
And you can track the profile changes here:
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
if(currentProfile != null){
fbUserId = currentProfile.getId();
if(!sharedPreferences.contains("UserName")){
editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
}
if(!sharedPreferences.contains("FbId")){
editor.putString("FbId",currentProfile.getId());
}
if(!sharedPreferences.contains("ProfilePicture")){
editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
}
editor.commit();
}
}
};