I am using the following code. I want the user's Date Of Birth, Email and Gender. Please help. How to retrieve those data?
This is my onViewCreated()
inside the Fragment.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup TextView.
mTextDetails = (TextView) view.findViewById(R.id.text_details);
// Set up Login Button.
LoginButton mButtonLogin = (LoginButton) view.findViewById(R.id.login_button);
// setFragment only if you are using it inside a Fragment.
mButtonLogin.setFragment(this);
mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.setReadPermissions("public_profile");
mButtonLogin.setReadPermissions("email");
mButtonLogin.setReadPermissions("user_birthday");
// Register a callback method when Login Button is Clicked.
mButtonLogin.registerCallback(mCallbackManager, mFacebookCallback);
}
This is my Callback Method.
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Shreks Fragment", "onSuccess");
Profile profile = Profile.getCurrentProfile();
Log.d("Shreks Fragment onSuccess", "" +profile);
// Get User Name
mTextDetails.setText(profile.getName() + "");
}
@Override
public void onCancel() {
Log.d("Shreks Fragmnt", "onCancel");
}
@Override
public void onError(FacebookException e) {
Log.d("Shreks Fragment", "onError " + e);
}
};
This question is related to
android
facebook-android-sdk
facebook-sdk-4.0
After Login
private void getFbInfo() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
Log.d(LOG_TAG, "fb json object: " + object);
Log.d(LOG_TAG, "fb graph response: " + response);
String id = object.getString("id");
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String gender = object.getString("gender");
String birthday = object.getString("birthday");
String image_url = "http://graph.facebook.com/" + id + "/picture?type=large";
String email;
if (object.has("email")) {
email = object.getString("email");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,last_name,email,gender,birthday"); // id,first_name,last_name,email,gender,birthday,cover,picture.type(large)
request.setParameters(parameters);
request.executeAsync();
}
Use this snippet for get all profile info
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
// Facebook Email address
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.v("LoginActivity Response ", response.toString());
try {
Name = object.getString("name");
FEmail = object.getString("email");
Log.v("Email = ", " " + FEmail);
Toast.makeText(getApplicationContext(), "Name " + Name, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
LoginManager.getInstance().logOut();
}
@Override
public void onError(FacebookException e) {
}
};
Use FB static method getCurrentProfile() of Profile class to retrieve those info.
Profile profile = Profile.getCurrentProfile();
String firstName = profile.getFirstName());
System.out.println(profile.getProfilePictureUri(20,20));
System.out.println(profile.getLinkUri());
You can use the GraphRequest class to issue calls to the Facebook Graph API to get user information. See https://developers.facebook.com/docs/android/graph for more info.
Add this line on Click on button
loginButton.setReadPermissions(Arrays.asList( "public_profile", "email", "user_birthday", "user_friends"));
Here's a working solution (2019): put this code inside your login logic;
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), 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";
Log.d("SignUpActivity", "Email: " + fbUserEmail + "\nName: " + fbUserFirstName + "\nID: " + fbUserId);
}
Log.d("SignUpActivity", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
setResult(RESULT_CANCELED);
Toast.makeText(SignUpActivity.this, "Login Attempt Cancelled", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(SignUpActivity.this, "An Error Occurred", Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
That's not the right way to set the permissions as you are overwriting them with each method call.
Replace this:
mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.setReadPermissions("public_profile");
mButtonLogin.setReadPermissions("email");
mButtonLogin.setReadPermissions("user_birthday");
With the following, as the method setReadPermissions()
accepts an ArrayList:
loginButton.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
Also here is how to query extra data GraphRequest:
private LoginButton loginButton;
private CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.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) {
Log.v("LoginActivity", response.toString());
// Application code
String email = object.getString("email");
String birthday = object.getString("birthday"); // 01/31/1980 format
}
});
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());
}
});
}
EDIT:
One possible problem is that Facebook assumes that your email is invalid. To test it, use the Graph API Explorer and try to get it. If even there you can't get your email, change it in your profile settings and try again. This approach resolved this issue for some developers commenting my answer.
You won't get Profile in onSuccess()
you need to implement ProfileTracker
along with registering callback
mProfileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
// Fetch user details from New Profile
}
};
Also don't forget to handle the start and stop of profile tracker
Now you will have a profile to get AccessToken from (solved the issue of null profile). You just have to use "https://developers.facebook.com/docs/android/graph#userdata" to get any data.
Following is the code to find email id, name and profile url etc
private CallbackManager callbackManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
//TODO on click of fb custom button call handleFBLogin()
callbackManager = CallbackManager.Factory.create();
}
private void handleFBLogin() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
if (isLoggedIn && Store.isUserExists(ActivitySignIn.this)) {
goToHome();
return;
}
LoginManager.getInstance().logInWithReadPermissions(ActivitySignIn.this, Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
runOnUiThread(new Runnable() {
@Override
public void run() {
setFacebookData(loginResult);
}
});
}
@Override
public void onCancel() {
Toast.makeText(ActivitySignIn.this, "CANCELED", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(ActivitySignIn.this, "ERROR" + exception.toString(), Toast.LENGTH_SHORT).show();
}
});
}
private void setFacebookData(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.i("Response", response.toString());
String email = response.getJSONObject().getString("email");
String firstName = response.getJSONObject().getString("first_name");
String lastName = response.getJSONObject().getString("last_name");
String profileURL = "";
if (Profile.getCurrentProfile() != null) {
profileURL = ImageRequest.getProfilePictureUri(Profile.getCurrentProfile().getId(), 400, 400).toString();
}
//TODO put your code here
} catch (JSONException e) {
Toast.makeText(ActivitySignIn.this, R.string.error_occurred_try_again, Toast.LENGTH_SHORT).show();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
This is worked for me, Hope to help someone (Using my own button not FB login button )
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_sign_in_user);
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) {
try {
Log.i("RESAULTS : ", object.getString("email"));
}catch (Exception e){
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException error) {
Log.i("RESAULTS : ", error.getMessage());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void signupwith_facebook(View view) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}
Source: Stackoverflow.com