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();
}
Related
My code is as shown below:
facebookButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(LogInActivity.this,
Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
//set login status
SessionManager.get(LogInActivity.this).setLoginStatus(true);
graphRequest(loginResult);
}
#Override
public void onCancel() {
// not called
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
// not called
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
});
private void graphRequest(LoginResult loginResult) {
showProgressDialog();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
if (object.has("email")) {
//store session manager
email = object.getString("email");
SessionManager.get(LogInActivity.this).setEmailId(email);
}
if (object.has("id")) {
faceBookId = object.getString("id");
picUrl = "https://graph.facebook.com/" + faceBookId
+ "/picture?type=large";
//store session manager
SessionManager.get(LogInActivity.this).setProfilePic(picUrl);
// downLoadImage(url);
}
if (object.has("name")) {
//store session manager
name = object.getString("name");
SessionManager.get(LogInActivity.this).setPersonName(name);
}
downLoadImage(picUrl, name, email, "0");
// Toast.makeText(getApplicationContext(), email, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
}
The problem here is , I am not able to get email id even after enabling Allow friends to include my email address in Download Your Information option in my facebook profile, is there any other way to get email id?
try it
String email = "";
try {
email = URLDecoder.decode(object.optString("email")
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
I'm using Facebook Android SDK 'com.facebook.android:facebook-android-sdk:4.13.1' version.
My issue with this Facebook Version is exactly same like this question. I need to redirect to my Home screen after clicking on Facebook Login button without reverting back to Login screen. Can this SDK version(4.13.1) solve/support this feature? Please help me.
loginButton = (LoginButton) findViewById(R.id.fb_login_button);
loginButton.setReadPermissions("public_profile email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if (AccessToken.getCurrentAccessToken() != null) {
RequestData();
}
}
#Override
public void onCancel() {
// code for cancellation
Toast.makeText(getBaseContext(), "Login Cancelled", Toast.LENGTH_SHORT).show();
Log.d("i am in ", "cancel method");
// Toast.makeText(getApplicationContext(),"Login as cancelled",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
Log.d("i am in ", "error method");
Toast.makeText(getApplicationContext(), "Internet Error occurred Please try again latter", Toast.LENGTH_SHORT).show();
/* Log.v("LoginActivity", e.getCause().toString());*/
}
});
private void RequestData() {
graphRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
String emailId;
String profilePicUrl;
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
if (response != null) {
try {
JSONObject data = response.getJSONObject();
username = json.getString("name");
emailId = json.getString("email");
}
catch (Exception e) {
e.printStackTrace();
}
}
CallingRetrofit(emailId,profilePicUrl);
LoginManager.getInstance().logOut();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
In CallingRetrofit function I'm passing intent to home screen if he is a authorized user.
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
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();
}
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!