I'm writing a Facebook Android app and one of the problems I'm encountering is getting users' email addresses. For all Facebook accounts except one, the email address is throwing an exception. Here's my code:
loginButton = (LoginButton) findViewById(R.id.login_button);
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
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)
{
SharedPreferences.Editor editor =
sharedPref.edit();
try
{
editor.putString("user_ID",
object.getString("id"));
user_ID = object.getString("id");
editor.putString("user_name." +
user_ID, object.isNull("name") ?
"" : object.getString("name"));
editor.putString("email_addr." +
user_ID, object.isNull("email") ?
"" : object.getString("email"));
editor.commit();
}
catch (Exception e)
{
Toast.makeText(LaunchPage.this, getString(R.string.login_error) + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email, gender, birthday, timezone, picture, locale, age_range");
request.setParameters(parameters);
request.executeAsync();
}
I've spent several days on this problem and I think I'm doing what was suggested in several other solutions posted, but my code still fails. I tried making my email address public in the failing Facebook accounts, but that didn't help.
Try this code:
add
setReadPermissionsin yourLoginButtonAlso make sure your
Emailis public in your Fb Account. OtherwiseGraph apiwill not return it.