I'm trying to get name and email from facebook login.
I'm using: compile 'com.facebook.android:facebook-android-sdk:4.+'
I can get into onSuccess but the code does not get into GraphRequest and I think that's why I can't get name and email (I'd also like get Profile picture)
I got the autogenerated code (GraphRequest) from facebook developer Explorer Api Graph
public class LoginActivity
{
LoginButton buttonLoginFacebook;
#Nullable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
buttonLoginFacebook = (LoginButton) findViewById(R.id.connectWithFbButton);
buttonLoginFacebook.setReadPermissions(Arrays.asList(
"public_profile", "email"));
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
FacebookSdk.addLoggingBehavior(LoggingBehavior.REQUESTS);
buttonLoginFacebook.setOnClickListener(this);
buttonLoginFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
//----->THE CODE JUMPS FROM HERE
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
mensajeFACEBOOK="TRYING TO GET NAME";
}
});
//----->TO HERE
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
}
This is how i do it. Hope this helps.
private void registerCallBackMethod(){
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
final String accessToken = loginResult.getAccessToken().getUserId();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject,
GraphResponse response) {
// Getting FB User Data and checking for null
Bundle facebookData = getFacebookData(jsonObject);
String email = "";
String first_name = "";
String last_name = "";
String profile_pic = "";
if (facebookData.getString("email") != null && !TextUtils.isEmpty(facebookData.getString("email")))
email = facebookData.getString("email");
else
email = "";
if (facebookData.getString("first_name") != null && !TextUtils.isEmpty(facebookData.getString("first_name")))
first_name = facebookData.getString("first_name");
else
first_name = "";
if (facebookData.getString("last_name") != null && !TextUtils.isEmpty(facebookData.getString("last_name")))
last_name = facebookData.getString("last_name");
else
last_name = "";
if (facebookData.getString("profile_pic") != null && !TextUtils.isEmpty(facebookData.getString("profile_pic")))
profile_pic = facebookData.getString("profile_pic");
else
profile_pic = "";
sendValues(first_name+" "+last_name,email, "", "", accessToken, "Facebook",profile_pic);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,last_name,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel () {
Log.d("TAG", "Login attempt cancelled.");
}
#Override
public void onError (FacebookException e){
e.printStackTrace();
Log.d("TAG", "Login attempt failed.");
deleteAccessToken();
}
}
);
}
private Bundle getFacebookData(JSONObject object) {
Bundle bundle = new Bundle();
try {
String id = object.getString("id");
URL profile_pic;
try {
profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?type=large");
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"));
} catch (Exception e) {
Log.d("TAG", "BUNDLE Exception : "+e.toString());
}
return bundle;
}
private void deleteAccessToken() {
AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null){
//User logged out
LoginManager.getInstance().logOut();
}
}
};
}
Actually GraphRequest.executeAsync() is an async method with a callback onCompleted so to read the data you need to do it inside the callback.
buttonLoginFacebook.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) {
//Read the data you need from the GraphResponse here like this:
try {
String firstName = response.getJSONObject().getString("first_name");
String lastName = response.getJSONObject().getString("last_name");
String email = response.getJSONObject().getString("email");
String id = response.getJSONObject().getString("id");
String picture = response.getJSONObject().getJSONObject("picture").getJSONObject("data").getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,first_name,last_name,picture.width(150).height(150)");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
Also included the profile picture field picture.width(150).height(150) as you asked
Related
In my android app i have done Facebook integration.Facebook login works fine.How can i get user's email id from Facebook integration in android?
please help.
thanks in advance.
Use permission and this code
loginButton.setReadPermissions(Arrays.asList( "email","user_birthday"));
and use Graph Api
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progressDialog.dismiss();
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("response: ", response + "");
Log.e("object: ", object + "");
try {
userfbData = new UserfbData();
userfbData.facebookID = object.getString("id").toString();
userfbData.email = object.getString("email").toString();
userfbData.name = object.getString("name").toString();
userfbData.gender = object.getString("gender").toString();
userfbData.birthday=object.getString("birthday").toString();
PrefUtils.setCurrentUser(userfbData,LoginActivity.this);
Log.d("flist","flist"+ userfbData.flist);
}catch (Exception e){
e.printStackTrace();
}
// Toast.makeText(LoginActivity.this,"welcome "+userfbData.name+userfbData.email+userfbData.gender+userfbData.birthday, Toast.LENGTH_LONG).show();
Toast.makeText(LoginActivity.this,"welcome "+ userfbData.name, Toast.LENGTH_LONG).show();
Intent intent=new Intent(LoginActivity.this,LogoutActivity.class);
startActivity(intent);
finish();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
Log.d("error","error"+e);
e.printStackTrace();
}
};
UserFbData
public class UserfbData {
public String name;
public String email;
public String facebookID;
public String gender;
public String birthday;
}
You need to make a GraphRequest call to get personal information of the logged in user such as id, name, email etc.
GraphRequest request = GraphRequest.newMeRequest(accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String email = object.getString("email");
} catch (JSONException e) {
}
}
}
);
Bundle parameters = new Bundle();
parameters.putString("fields","email");
request.setParameters(parameters);
request.executeAsync();
I implemented Facebook in app and fetched name,email and id from graph api,Now i cannot get email it from graph api and i passed id,name,email fields but got only id,name but not email.Is it change any privacy policy from facebook.
I'm Using https://graph.facebook.com/me?access_token=(token here)&fields=id,name,email
Try With This Running successfully
private void facebookLogin() {
mFaceBookloginButton = (LoginButton) findViewById(R.id.login_button);
mFaceBookloginButton.setReadPermissions("public_profile");
mFaceBookloginButton.setReadPermissions("email");
callbackManager = CallbackManager.Factory.create();
mFaceBookloginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
MyLog.debug("Name" + loginResult.getAccessToken(), ActivityLogin.class);
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
MyLog.debug("Pic Url" + profile.getProfilePictureUri(200, 200), ActivityLogin.class);
MyLog.debug("User Name" + profile.getFirstName(), ActivityLogin.class);
MyLog.debug("User Email" + profile.getLastName(), ActivityLogin.class);
}
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
FacebookUser facebookUser = null;
try {
if (object != null) {
facebookUser = new FacebookUser();
if (object.has("id")) {
facebookUser.setId(object.getString("id"));
}
if (object.has("first_name")) {
facebookUser.setFirst_name(object.getString("first_name"));
}
if (object.has("last_name"))
facebookUser.setLast_name(object.getString("last_name"));
if (object.has("email"))
facebookUser.setEmail(object.getString("email"));
}
if (facebookUser != null) {
hitSocialLogin(facebookUser);
LoginManager.getInstance().logOut();
}
} catch (Exception e) {
MyLog.printException(e);
} finally {
LoginManager.getInstance().logOut();
}
}
});
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() {
MyLog.debug("on Cancel", ActivityLogin.class);
}
#Override
public void onError(FacebookException exception) {
MyLog.debug("on Cancel" + exception, ActivityLogin.class);
}
});
}
I'm using Facebook SDK 4.16.1 by using Profile I could get first name, last name, name and id my code is like this
public class LoginActivity extends Activity {
String id, fname, lname, email, name, gender, locale, verified;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginactivity);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList(Constants.FACEBOOK_PERMISSIONS));
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
FB_TOKEN=loginResult.getAccessToken().getToken();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
response.getError();
Log.e("JSON:", object.toString());
try {
email = object.getString("email");
gender = object.getString("gender");
locale = object.optString("locale");
verified = object.optString("verified");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,birthday,first_name,last_name,email,gender,verified,locale");
request.setParameters(parameters);
request.executeAsync();
id = profile.getId();
fname = profile.getFirstName();
lname = profile.getLastName();
name = profile.getName();
nextActivity(profile);
Toast.makeText(getApplicationContext(), "Logging in...", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
loginButton.registerCallback(callbackManager, callback);
}
}
My constants looks like this
public static final String[] FACEBOOK_PERMISSIONS = new String[] {
"public_profile",
"user_friends",
"email" };
I'm trying to get the email, gender, locale and if its already verified. How will I get the other information? Mine are always null expect for the items that is get by Profile
Update
I update my GraphRequest like this
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
response.getError();
Log.e("JSON-RESULT:", object.toString());
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(object.toString());
email = jsonObject.getString("email");
gender = jsonObject.getString("gender");
locale = jsonObject.getString("locale");
verified = jsonObject.getString("verified");
Log.e(TAG, email + " This is the email");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,birthday,first_name,last_name,email,gender,verified,locale");
request.setParameters(parameters);
request.executeAsync();
In my Logcat it shows that I set the email and the others correctly but it doesn't go inside GraphRequest when you put breakpoints, and because of this my global variable email is still null. Even if in Log.e("JSON:", object.toString()); and Log.e(TAG, email + " This is the email"); it shows I get and set the values. I'm wondering how can I get the values of Bundle?
Try using below code to fetch other info.....
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// Log.d("Login", "onSuccess");
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
email = me.optString("email");
String id = me.optString("id");
String email=me.optString("email");
String name= me.optString("name");
String gender= me.optString("gender");
String verified= me.optBoolean("is_verified") + "";
}
}
}).executeAsync();
}
#Override
public void onCancel () {
// Log.d("Login", "onCancel");
}
#Override
public void onError (FacebookException e){
// Log.d("Login", "onError " + e);
}
};
I added Facebook SDK to my android app. I used callBackManager to handle the login button. Now I'm logged to Facebook and I want to save my fb profile information (profile photo, cellphone, name, birthdate..) before calling the function goRegisterActivity(). Any help?
// Handle Facebook Login Button
callbackManager = CallbackManager.Factory.create();
facebookLoginBtn = (LoginButton) findViewById(R.id.login_facebook_btn);
facebookLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
//Go to register first step activity
goRegisterActivity();
}
#Override
public void onCancel() {
//Do nothing
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(),"Oups! can't login Facebook. Please try again later.", Toast.LENGTH_SHORT)
.show();
}});
}
Call the graph API in the onSuccess() method:
facebookLogin.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.i("LoginActivity", response.toString());
// Get facebook data from login
Bundle bFacebookData = getFacebookData(object);
emailStr = bFacebookData.get("email").toString();
fnameStr = bFacebookData.get("first_name").toString();
lnameStr = bFacebookData.get("last_name").toString();
facebookIdStr = bFacebookData.get("idFacebook").toString();
genderStr = bFacebookData.get("gender").toString();
dp_url = bFacebookData.get("profile_pic").toString();
}
});
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();
}
And The getFacebookData(object) method should be like:
private Bundle getFacebookData(JSONObject object) {
try {
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"));
System.out.println("BUNDLEEE: "+bundle);
return bundle;
} catch (JSONException e) {
e.printStackTrace();
}
return bundle;
}
This works for me. You can use ProfileTracker also, but I find this more reliable.
Thanks
Heres the method im using and it returns the id and name no problems.
// Private method to handle Facebook login and callback
private void onFblogin() {
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "public_profile"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
if (response.getError() != null) {
// handle error
System.out.println("ERROR");
} else {
System.out.println("Success");
try {
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
// String str_email = json.getString("email");
String str_email = json.getString("email");
String str_name = json.getString("name");
String str_id = json.getString("id");
//
// Save your info
settings = getSharedPreferences("login_details", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", str_name);
editor.putString("email", str_email);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).executeAsync();
Intent openNewActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(openNewActivity);
}
#Override
public void onCancel() {
Log.d("TAG_CANCEL", "On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d("TAG_ERROR", error.toString());
}
});
}
The problem i have is that email doesnt return.
Ive tested the permissions with another app that can get my email when i sign in so permissions seem fine. Im assuming im calling it wrong now.
Try this just before executing your AsyncTask.
You can do this inside your onSuccess() method of the FacebookCallback().
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback(){
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
try {
email = jsonObject.getString("email");
fullName = jsonObject.getString("name");
} catch (Exception e) {
Log.d("FacebookActivity", "onCompleted - undetermined FB exception");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override public void onCancel(){}
#Override public void onError(){}
Good luck!