I trying get email of user but I can't. profile.getProperty("email").toString(), profile.getEmail()..
I don't find solution.
Thanks u.
private void updateUI() {
Profile profile = Profile.getCurrentProfile();
//if (enableButtons && profile != null) {
if (profile != null) {
System.out.println("Nombre: "+profile.getFirstName()+" "+profile.getLastName());
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
First you need to set permission like
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
and in your Activity do this
private LoginButton loginButton;
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"));
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) {
// Application code
Log.v("LoginActivity", response.toString());
}
});
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());
}
});
}
Related
I used Facebook Login in my app as registering. Facebook API part worked well and after I got parameters I saved them to session, too.
For second part, I create a user data in MySQL via PHP Slim Framework.
I posted body with Retrofit. After user authentication I got Facebook data perfectly.
Everything is good but somehow Retrofit works onFailure method instead of onResponse method. (I got a little "user added" message in response) And gives this error(below)
Debug Mode Screenshot: Click to See
MainActivity
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
TextView text;
Button button;
ImageView image;
ProgressDialog mDialog;
String accessToken;
//SESSION
String user_email;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPreferences.edit();
goIfTokenExist();
//
text = findViewById(R.id.text);
image = findViewById(R.id.image);
//
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Retrieving data...");
mDialog.show();
accessToken = loginResult.getAccessToken().getToken();
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
mDialog.dismiss();
getData(object);
goIfTokenExist();
}
});
//Graph API
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
if (AccessToken.getCurrentAccessToken() != null) {
text.setText(AccessToken.getCurrentAccessToken().getUserId());
}
}
public void getData(JSONObject obj) {
try {
URL profile_picture = new URL("https://graph.facebook.com/" + obj.getString("id") + "/picture?width=250&height=250");
Glide.with(this).load(profile_picture.toString()).into(image);
text.setText(
"ID: " + obj.getString("id") + "\n" +
"NAME: " + obj.getString("name") +
"EMAIL: " + obj.getString("email") +
"BIRTHDAY: " + obj.getString("birthday")
);
//SAVE SESSIONS
editor.putString("facebook_id", obj.getString("id"));
editor.putString("facebook_email",obj.getString("email"));
editor.putString("facebook_name",obj.getString("name"));
editor.putString("facebook_birthday",obj.getString("birthday"));
editor.putString("facebook_username",""+obj.getString("name").replaceAll("\\s+","").toLowerCase());
editor.commit();
UserFacebook userNew = new UserFacebook(
obj.getString("id"),
obj.getString("email"),
obj.getString("name"),
obj.getString("birthday"),
obj.getString("name").replaceAll("\\s+","").toLowerCase());
API_Service service = Client.getRetrofitInstance().create(API_Service.class);
Call<UserFacebook> userFacebookCall = service.addFacebookUser(userNew);
userFacebookCall.enqueue(new Callback<UserFacebook>() {
#Override
public void onResponse(Call<UserFacebook> call, Response<UserFacebook> response) {
Toast.makeText(MainActivity.this, "done", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<UserFacebook> call, Throwable t) {
Toast.makeText(MainActivity.this, "was wrong", Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
public void goIfTokenExist() {
//FORWARD TO HOME IF TOKEN IS VALID
if (isLoggedIn() == true) {
startActivity(new Intent(MainActivity.this, ForwardDeneme.class));
} else {
Toast.makeText(MainActivity.this, "no token!", Toast.LENGTH_SHORT).show();
}
}}
API_Service (interface)
public interface API_Service {
#Headers("Content-Type: application/json")
#POST("api/user/add")
Call<UserFacebook> addFacebookUser(#Body UserFacebook userFacebook);}
Client
public class Client {
private static Retrofit retrofit = null;
private static String BASE_URL = "http://192.168.1.102/myWebsite/public/index.php/";
private Client() {}
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}}
Thanks in advance.
Change the Response from call, from UserFacebook to String or UserFacebook need a String parameter called user_added (depending on the json you are receiving)
I am using this code...
I used the logInWithPublishPermissions for login...
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
java.util.List<String> permissionNeeds = Arrays.asList("publish_actions");
//this loginManager helps you eliminate adding a LoginButton to your UI
// LoginManager = LoginManager.getInstance();
LoginManager.getInstance().logInWithPublishPermissions(
FacebookShareActivity.this,
Arrays.asList("publish_actions"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
sharePhotoToFacebook();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
}
});
sharePhotoToFacebook
private void sharePhotoToFacebook(){
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("Caption")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content,shareCallback);
// Toast.makeText(getApplicationContext(),"Snapshot shared On Facebook",Toast.LENGTH_SHORT).show();
//shareDialog.registerCallback(callbackManager, FacebookCallback<Sharer.Result>(), REQUEST_CODE);
}
But I want the app ask for permission it's not show the dialog of ask permission of publish.
Try this way for facebook login:
#Bind(R.id.login_button_fb)
LoginButton login_button_fb;
.
.
.
.
login_button_fb.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "public_actions"));
login_button_fb.setFragment(LoginFragment.this);
login_button_fb.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
addToMainQueue(TCRequestGenerator.loginWithFacebook(loginResult.getAccessToken().getToken()));
}
#Override
public void onCancel() {
LoginManager.getInstance().logOut();
}
#Override
public void onError(FacebookException error) {
showAlert(error.getMessage());
LoginManager.getInstance().logOut();
}
});
I am trying to handle Facebook and Google login into a single activity
The google login works but Facebook login is not showing the request permission dialog. When I click login with Facebook button I expect to see permissions dialog for public profile and email. Although the dialog does not appear it seems that I am signed in as Login with Facebook changes to Logout. Is there any better way of doing this?
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 1;
private GoogleApiClient googleClient;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
SignInButton googleButton = (SignInButton)findViewById(R.id.google_button);
LoginButton facebookBtn = (LoginButton)findViewById(R.id.fb_login_button);
Button emailButton = (Button)findViewById(R.id.email_button);
googleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
initGoogleSignIn();
initFacebookSignIn(facebookBtn);
}
private boolean isLoggedInByFacebook(){
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
private void initGoogleSignIn(){
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(googleClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done" and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
finish();
}
}
private void initFacebookSignIn(LoginButton facebookBtn){
if(isLoggedInByFacebook()) {
finish();
}else{
callbackManager = CallbackManager.Factory.create();
facebookBtn.setReadPermissions(Arrays.asList(
"public_profile","email"));
// Callback registration
facebookBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginResult.getAccessToken().getUserId();
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Log.i("Response",response.toString());
String email = response.getJSONObject().getString("email");
String name = response.getJSONObject().getString("name");
finish();
}catch (JSONException e){
Log.e(TAG,"Error getting facebook email", e);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
Log.e(TAG,"Error in facebook sign in", exception);
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
api.loginGoogle(acct.getIdToken()).subscribe(new Action1<User>() {
#Override
public void call(User user) {
api.getWeather(-31.0, 115.0).subscribe(new Action1<WeatherResponse>() {
#Override
public void call(WeatherResponse weatherResponse) {
}
});
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
System.out.println(throwable);
}
});
} else {
System.out.println(result.getStatus());
}
}else { //facebook
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
}
try this:
Declare the variables:
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
com.facebook.Profile profile;
private ProfileTracker mProfileTracker;
in your onCreate() method..
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
updateWithToken(AccessToken.getCurrentAccessToken());
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
updateWithToken(newToken);
}
};
accessTokenTracker.startTracking();
Now in updateWithToken() method
private void updateWithToken(AccessToken currentAccessToken) {
if (currentAccessToken != null) {
LoginManager.getInstance().logOut();
} else {
}
}
Now in the callback manager you have to track user's current profile
List<String> permissionNeeds = Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends");
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
// profile2 is the new profile
profile = profile_new;
if (profile_new != null)
Log.v("facebook - profile", profile_new.getFirstName());
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
if (profile != null)
Log.v("facebook - profile", profile.getFirstName());
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.v("FACEBOOK LOGIN", response.toString());
fb_id = object.getString("id");
fb_name = object.getString("name");
fb_gender = object.getString("gender");
fb_email = object.getString("email");
fb_birthday = object.getString("birthday");
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", e.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
Log.d("FACEBOOK ERRROR", "cancelled");
}
#Override
public void onError(FacebookException exception) {
Log.d("FACEBOOK ERRROR", exception.toString());
});
If you don't mind using a WebView then try CloudRail for social login, it's very simple to use.
https://github.com/CloudRail/cloudrail-si-android-sdk
I wrote code for connecting with Facebook and extracting username,email ID and Profile link .All the extracted details displays in different activity on the click of a button.But I wanted it to display it in the same actiivty as soon the login process is completed successfully.which means I need to edit the code after onSuccess but I don't no how to get the code
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
Button share,details;
ShareDialog shareDialog;
LoginButton login;
ProfilePictureView profile;
Dialog details_dialog;
TextView details_txt;
TextView details_txtx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
login = (LoginButton)findViewById(R.id.login_button);
profile = (ProfilePictureView)findViewById(R.id.picture);
shareDialog = new ShareDialog(this);
share = (Button)findViewById(R.id.share);
details = (Button)findViewById(R.id.details);
login.setReadPermissions("public_profile email");
share.setVisibility(View.INVISIBLE);
details.setVisibility(View.INVISIBLE);
details_dialog = new Dialog(this);
details_dialog.setContentView(R.layout.dialog_details);
details_dialog.setTitle("Details");
details_txtx = (TextView)details_txtx.findViewById(R.id.details_tetx);
details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
details_dialog.show();
}
});
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(AccessToken.getCurrentAccessToken() != null) {
share.setVisibility(View.INVISIBLE);
details.setVisibility(View.INVISIBLE);
profile.setProfileId(null);
}
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShareLinkContent content = new ShareLinkContent.Builder().build();
shareDialog.show(content);
}
});
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult ) {
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
public void RequestData(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if(json != null){
String text = "<b>Name :</b> "+json.getString("name")+"<br><br><b>Email :</b> "+json.getString("email")+"<br><br><b>Profile link :</b> "+json.getString("link");
details_txt.setText(Html.fromHtml(text));
profile.setProfileId(json.getString("id"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
To be Clear: All i wanted is to display the extracted details in the same activity after a successful login can you please help with it.?
please check the following code
protected void connectToFacebook() {
ArrayList<String> list = new ArrayList<String>();
list.add("email");
// LoginManager.getInstance().logInWithReadPermissions(this, list);
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().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 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";
callApiForCheckSocialLogin(fbUserId, fbUserFirstName, fbUserEmail, fbUserProfilePics, "fb");
}
Log.v("FaceBook Response :", response.toString());
}
});
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);
Utilities.showToast(mActivity, "" + exception);
}
});
}
I have the following class that I instantiate from my fragment:
public class FacebookLogin {
private CallbackManager mCallbackManager;
private LoginButton lButton;
private AccessToken accessToken;
private Profile profile;
private static final String TAG = "FacbookLogin";
public FacebookLogin(Context c) {
FacebookSdk.sdkInitialize(c);
mCallbackManager = CallbackManager.Factory.create();
Log.i(TAG, " Constructor called");
}
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, " logged in...");
AccessToken accessToken = loginResult.getAccessToken();
profile = Profile.getCurrentProfile(); //Access the profile who Is the person login i
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Log.i(TAG, " Error");
Log.e(TAG, e.getMessage());
}
};
public void setCallback(LoginButton lButton) {
lButton = lButton;
lButton.registerCallback(mCallbackManager, mCallback);
Log.i(TAG, " setCallback called");
}
public CallbackManager getCallbackManager(){
return mCallbackManager;
}
public Profile getProfile() {
return profile;
}
}
And here Is my fragment-class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fLogin = new FacebookLogin(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.login, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
final LoginButton loginButton = (LoginButton) getView().findViewById(R.id.login_button);
final TextView infoText = (TextView) getView().findViewById(R.id.text_details);
loginButton.setFragment(this);
loginButton.setReadPermissions("user_friends");
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(TAG, " Button clickde");
fLogin.setCallback(loginButton); //Let's register a callback
profile = fLogin.getProfile();
if (profile != null) {
Log.i(TAG, profile.getName());
} else {
Log.i(TAG, "NULL....... inside onresume");
}
}
});
}
As you can see, Im trying to get the users profile when you click on the button. The login works, but the problem I have Is that when I click Login, else-statement Is executed and prints out NULL...... However, when I click Logout, I get the correct information, and the profile-object Is no longer NULL.
Why Is It null the first time I click on the button (login), and then becomes true when I click on It again (logout)?
When I place the profile-code inside onResume, It works. Why?
#Override
public void onResume()
{
super.onResume();
profile = fLogin.getProfile();
if (profile != null) {
Log.i(TAG, profile.getName()); //Prints out directly when I hit the button
} else {
Log.i(TAG, "NULL....... inside onresume");
}
}
Use an interface for solving this.
In the FacebookLogin class
OnFacebookListener facebookListener;
public interface OnFacebookListener{
void onFacebookLoggedIn(Profile profile);
}
public void setFacebookListener(OnFacebookListener onfacebooklistener){
this.facebookListener=onfacebooklistener;
}
and then
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
profile = Profile.getCurrentProfile();
facebookListener.onFacebookLeggedIn(profile);
}
then in your fragment
fLogin.setFacebookListener(new OnFacebookListener(){
#Override
public void onFacebookLoggedIn(Profile profile){
//Do whatever you want to do with profile
}
});
Hope this works for you :D
You need to use Facebook Graph Api for getting user details from facebook. Here is the login code I used for my project.
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
/**
* Current SDK uses GraphAPI to retrieve data from facebook
*/
final String token = loginResult.getAccessToken().getToken();
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
String name1 = jsonObject.optString("name");
String email1 = jsonObject.optString("email");
JSONObject cover = jsonObject.optJSONObject("cover");
String coverPic = cover.optString("source");
String id = jsonObject.optString("id");
String userdp = "https://graph.facebook.com/" + id + "/picture?type=large";
loginSocial(Constants.POST_METHOD_FACEBOOK, token);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,cover");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Login Cancelled... Please try again later", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException exception) {
Toast.makeText(getApplicationContext(), "Login Failed... Please try again later", Toast.LENGTH_LONG).show();
}
});