Unable to fetch facebook profile picture, to insert in ImageView - android

I am unable to fetch the facebook profile picture, in order to display it in my fragment. Name, Birthday and link is fetched successfully, however the application stops working when I try to fetch the profile picture. How to get rid of this situation?
private FacebookCallback<LoginResult> callback=new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken=loginResult.getAccessToken();
Profile profile=Profile.getCurrentProfile();
//DisplayMessage(profile);
GraphRequest request=GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try{
tv1=(TextView)getView().findViewById(R.id.name);
tv1.setText("Name : " + object.getString("name"));
tv2=(TextView)getView().findViewById(R.id.birthday);
tv2.setText("BirthDay : " + object.getString("birthday"));
tv3=(TextView)getView().findViewById(R.id.id);
tv3.setText("link : " + object.getString("link"));
String id=object.getString("id");
Bitmap mBitmap = getFacebookProfilePicture(id);
img.setImageBitmap(mBitmap);
/*Toast.makeText(getActivity().getApplicationContext(), object.getString("name") + object.getString("birthday") +object.getString("link")
, Toast.LENGTH_SHORT).show();*/
}catch (JSONException e){
e.printStackTrace();
}
}
});
Bundle parameters= new Bundle();
parameters.putString("fields","name,birthday,link");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
};
public Bitmap getFacebookProfilePicture(String userID) {
Bitmap bitmap = null;
try {
URL imageURL = new URL("https://graph.facebook.com/" + userID
+ "/picture?type=large");
bitmap = BitmapFactory.decodeStream(imageURL.openConnection()
.getInputStream());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}

Everything you can get.Here is code.
private CallbackManager callbackManager;
private LoginButton loginButton;
in OnCreate(){
loginButton = (LoginButton) findViewById(R.id.login_button);
// don't forget to give this.
loginButton.setReadPermissions(Arrays.asList("public_profile,email,user_birthday"));
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDetails();
}
});
}
private void getDetails() {
//for facebook
// FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
//register callback object for facebook result
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
try {
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
String facebook_id = profile.getId();
String f_name = profile.getFirstName();
String l_name = profile.getLastName();
profile_image = profile.getProfilePictureUri(400, 400).toString();
}
String email_id = jsonObject.getString("email"); //email id
} catch (JSONException e) {
Logger.logError(e);
}
}
});
This surely works.
Check whether you are using this.
com.facebook.android:facebook-android-sdk:4.0.0

For a quick solution you can get profile picture of user with:
String profilePictureUrl = "https://graph.facebook.com/"+userID+"/picture?width=500&height=500";
And download with your image loader library to your image view.
Edit:
This is a simple ImageLoading library for Android (old but good)
https://github.com/nostra13/Android-Universal-Image-Loader
Easy to use:
Add it to your project as a gradle dependency.
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(profilePictureUrl, yourImageView);

I am using like :
public void getUserDetailsFromFB(AccessToken accessToken) {
GraphRequest req=GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Toast.makeText(getApplicationContext(),"graph request completed",Toast.LENGTH_SHORT).show();
try{
String email = object.getString("email");
String birthday = object.getString("birthday");
String gender = object.getString("gender");
String name = object.getString("name");
String id = object.getString("id");
String photourl =object.getJSONObject("picture").getJSONObject("data").getString("url");
}catch (JSONException e)
{
Toast.makeText(getApplicationContext(),"graph request error : "+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(large)");
req.setParameters(parameters);
req.executeAsync();
}
Then use Picasso like : Picasso.with(context).load(photourl).into(imageView);
Example Json format here :
{
"id": "10204968538960870",
"name": "Yasin KaƧmaz",
"email": "yasin_5775#hotmail.com",
"gender": "male",
"birthday": "12/06/1994",
"picture": {
"data": {
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/v/t1.0..."
}
}
}
You can try Graph Api to see example Json format in : Graph Api Explorer

Related

Can't get name and email from facebook

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

Cannot get values from GraphRequest Facebook

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);
}
};

Check in android if facebook-mail exists or not

I want to check in my android app if the user's email Facebook exists or not and if it's not exist, set it as "No mail found".
The code is right but when I click the Facebook button nothing happened because my inexistent email cause an error.
I have already check with my user token and my Facebook account doesn't have an email. Obviously it works perfectly without the email string.
This is my code:
loginButtonFb.setReadPermissions("user_friends", "email");
loginButtonFb.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
loginResult.getAccessToken().getUserId(),
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
JSONObject data = response.getJSONObject();
login_name = data.getString("name");
String idFb = data.getString("id");
String mailFb = data.getString("email");
String method = "loginFb";
BackgroundTaskLogin backgroundTask = new BackgroundTaskLogin(mContext);
backgroundTask.execute(method, login_name, idFb, mailFb);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
}
#Override
public void onCancel() {
Toast.makeText(mContext, "Login attempt canceled.", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException e) {
Toast.makeText(mContext, "Login attempt failed.", Toast.LENGTH_LONG).show();
}
});
I have solved the problem. I have declared String mailFb as universal String.
The other part of the code is below:
loginButtonFb.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
loginResult.getAccessToken().getUserId(),
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
JSONObject data = response.getJSONObject();
login_name = data.getString("name");
String idFb = data.getString("id");
if(!data.isNull("email")){
mailFb = data.getString("email");
}
mailFb = "Mail not found";
String method = "loginFb";
BackgroundTaskLogin backgroundTask = new BackgroundTaskLogin(mContext);
backgroundTask.execute(method, login_name, idFb, mailFb);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
}

Android Facebook Login- Profile is null

Trying to integrate Facebook Login in android app. The login and logout is working fine but sometimes even after login in, profile is still null. As soon as I get the details from Facebook I logout. I referred to some other questions on Stackoverflow, and applied it in the code but somewhere still something is going wrong and not able to figure it out.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.login_activity);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.btnFacebookSignin);
loginButton.setReadPermissions("public_profile, email");
loginButton.registerCallback(callbackManager, facebookCallback);
}
FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if(Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
Log.v("facebook - profile", profile2.getFirstName());
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
}
else {
Profile profile = Profile.getCurrentProfile();
Log.v("facebook - profile", profile.getFirstName());
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
String name = profile.getName();
Uri pictureUri = profile.getProfilePictureUri(200, 200);
String email = object.optString("email");
String uid = object.optString("id");
try {
sendLogin(uid, name, email, pictureUri.toString(), "fb");
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
facebookLogout();
} else {
facebookLogout();
Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
}
};
public void facebookLogout() {
LoginManager.getInstance().logOut();
}
Try this Code I hope Its Work..
facebookimage(object.getString("id"));
This is Method:
private void facebookimage(String id) {
new getFacebookImage(id).execute();
}
This is AsyncTask class to get Profile Image on Facebook ;
private class getFacebookImage extends AsyncTask {
String userID;
Bitmap camera;
public getFacebookImage(String id) {
userID=id;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object[] params) {
URL imageURL = null;
Bitmap bitmap=null;
try {
imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("String Image",""+bitmap);
camera=bitmap;
return bitmap;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if(camera != null){
Log.e("Image Load","UPload image");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
camera.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte imageInByte[] = stream.toByteArray();
String encodedImage = Base64.encodeToString(imageInByte, Base64.DEFAULT);
DataBase.setUserImage(LoginActivity.this,encodedImage);
}
}
}
Initially I was getting only id and email in JSONObject object of onCompleted. Even though I set permissions like "public_profile" and "email" which is sufficient enough to get the id, name, email and profile picture from facebook. But somewhere I went wrong and didn't understand and added Profile and did getProfile() so I can get the name and profile picture. Then other problem arised was even after login perfectly, I was getting null profile sometimes(may be once in 5 times). For that had to put Profile Tracker and this was because Profile works Asynchronously(was too confusing for me as you have to put trackers and start & stop tracking).
Then I realized where I went wrong. In the bundle where we need to mention what all we want in the json object as reply, I had only mentioned "id". So now in the below code I added "name" and "email" as well. So in the JSONObject object response I get the name and email as well.
And for profile picture I saw How can I display the users profile pic using the facebook graph api? and implemented this using Uri builder Use URI builder in Android or create URL with variables . So with this I removed the use of Profile completely and still getting all the data I wanted.
This answer is the mixture of both the answers mentioned by Destro - Android Facebook Login- Profile is null & How to get email id From Android Facebook SDK 4.6.0?
FacebookCallback<LoginResult> facebookCallback = 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) {
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
String uid = object.optString("id");
String email = object.optString("email");
String name = object.optString("name");
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("graph.facebook.com")
.appendPath(uid)
.appendPath("picture")
.appendQueryParameter("width", "1000")
.appendQueryParameter("height", "1000");
Uri pictureUri = builder.build();
try {
sendLogin(uid, name, email, pictureUri.toString(), "fb");
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
facebookLogout();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
}
};
public void facebookLogout() {
LoginManager.getInstance().logOut();
}

Android - Facebook API returns no email

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!

Categories

Resources