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)
Related
Here in my Main activity and I follow all the facebook Concole Methood.
When I tried to run the app.it shows an error that
Login error: There was an error while login your app, try again later
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginButton = findViewById(R.id.login_button);
textView1 = findViewById(R.id.tv1);
textView2 = findViewById(R.id.tv2);
textView3 = findViewById(R.id.tv3);
circleImageView = findViewById(R.id.profile_pic);
callbackManager = CallbackManager.Factory.create();
loginButton.setPermissions(Arrays.asList("first_name","last_name","email","id","image_url"));
checkLoginStatus();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
}
#Override
public void onCancel()
{
}
#Override
public void onError(FacebookException error)
{
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker accessTokenTracker=new AccessTokenTracker()
{
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken)
{
if(currentAccessToken==null)
{
textView1.setText("");
textView2.setText("");
textView3.setText("");
circleImageView.setImageResource(0);
Toast.makeText(MainActivity.this,"User Logged out",Toast.LENGTH_LONG).show();
}
else
{
loadUserProfile(currentAccessToken);
}
}
};
private void loadUserProfile(AccessToken newacesstoken)
{
GraphRequest request=GraphRequest.newMeRequest(newacesstoken,new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted(JSONObject object, GraphResponse response)
{
try
{
String first_name=object.getString("first_name");
String last_name=object.getString("last_name");
String email=object.getString("email");
String id=object.getString("id");
String image_url = "https://graph.facebook.com/" + id + "/picture?type=normal";
textView1.setText(first_name +" "+last_name);
textView2.setText(email);
textView3.setText(id);
//RequestOptions requestOptions = new RequestOptions();
//requestOptions.dontAnimate();
Picasso.get().load(image_url).into(circleImageView);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,last_name,email,id,image_url");
request.setParameters(parameters);
request.executeAsync();
}
private void checkLoginStatus()
{
if(AccessToken.getCurrentAccessToken()!=null)
{
loadUserProfile(AccessToken.getCurrentAccessToken());
}
}
}
I am creating an application to upload a photo to store on the server. However when sending the request via Post appears the following error:
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded' not supported]
I already researched everything, saw some alternatives but none came to solve my problem. I do not know how to come up with a solution.
My API Service:
#RestController
#RequestMapping(value = "/api")
public class Services {
#Autowired
private PacienteRepository pr;
#GetMapping("/pacientes")
public List<Paciente> listaPaciente() {
return pr.findAll();
}
#RequestMapping(value = "/paciente", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public Paciente cadastraPaciente(#RequestBody Paciente paciente) {
System.out.println(paciente.foto);
return pr.save(paciente);
}
}
My app:
public class MainActivity extends AppCompatActivity {
public static final String REGISTER_URL = "http://192.168.1.8:8080/api/paciente";
public static final String KEY_IMAGE = "foto";
String foto = "null";
public static final String TAG = "LOG";
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button enviar = (Button) findViewById(R.id.enviar);
enviar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerForms();
}
});
}
public void tirarFoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Bundle bundle = data.getExtras();
if (bundle != null) {
Bitmap img = (Bitmap) bundle.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.JPEG, 100, stream);
foto = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
Toast toast = Toast.makeText(getApplicationContext(), "Foto anexada", Toast.LENGTH_LONG);
toast.show();
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public void registerForms() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
/*if (response.contains("Erro")) {
//progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Erro ao enviar", Toast.LENGTH_LONG).show();
Log.i(TAG, "Lat: " + "Caiu aqui");
} else {*/
//progressDialog.dismiss();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
Toast.makeText(MainActivity.this, "Enviado com sucesso!", Toast.LENGTH_LONG).show();
startActivity(intent);
//}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
Log.i(TAG, "Lat: " + error.getMessage());
Log.i(TAG, "String: " + foto);
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
String requestBody = ""; //The request body goes in here.
try {
return requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> map = new HashMap<String, String>();
map.put("Content-Type","application/x-www-form-urlencoded");
map.put(KEY_IMAGE, "foto1");
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
I am using the following version of volley:
implementation 'com.android.volley:volley:1.1.1'
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();
}
});