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
Related
I have an app that requires the detection of location services (FINE_LOCATION) which requires either data or wifi to be enabled as well as the Location or (GPS) to be enabled as well.
I have managed to work around this if one condition is disabled but what I need is if all three services are disabled the app should walkthrough the user to enable them all one after another.
Is there a way of creating a loop or some kind of variable listener to see if all conditions are met?
public class dblogin extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
MaterialEditText email, password;
Button login, register, anon;
CheckBox loginState,tacState;
TextView tacAgree;
int responseData = 0;
SharedPreferences sharedPreferences;
private final int REQUEST_LOCATION_PERMISSION = 1;
boolean GPS_ACCESS = false;
boolean WLAN_ACCESS = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dblogin);
if(GPS_ACCESS&&WLAN_ACCESS)
{
requestLocationPermission(); //Requires Permission to Location
}
else
{
requestWLANAccess(); //WIFI IS OFF
requestGPSAccess(); //LOCATION is OFF
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#Override
public void onPermissionsGranted(int requestCode, List<String> list) {
register= findViewById(R.id.register);
login= findViewById(R.id.login);
anon= findViewById(R.id.anon);
login.setEnabled(true);
register.setEnabled(true);
anon.setEnabled(true);
login.setText("Login");
register.setBackgroundColor(Color.parseColor("#008577"));
anon.setBackgroundColor(Color.parseColor("#008577"));
// Some permissions have been granted
// ...
//Toast.makeText(this, "Permission is already granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionsDenied(int requestCode, List<String> list) {
// Some permissions have been denied
// ...
Toast.makeText(this, "Please allow access to location to continue using the app.", Toast.LENGTH_SHORT).show();
ViewGroup vg =findViewById(R.id.myView);
vg.invalidate();
register= findViewById(R.id.register);
login= findViewById(R.id.login);
anon= findViewById(R.id.anon);
register.setEnabled(false);
anon.setEnabled(false);
login.setText(R.string.grantpermission);
register.setBackgroundColor(Color.parseColor("#ffffff"));
anon.setBackgroundColor(Color.parseColor("#ffffff"));
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestLocationPermission();
}
});
}
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(this, perms)) {
//Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
onAccessGranted();
}
else {
EasyPermissions.requestPermissions(this, "PLEASE GRANT ACCESS TO LOCATION SERVICES", REQUEST_LOCATION_PERMISSION, perms);
}
}
public void requestGPSAccess(){
//GPS is not ON
LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
disbaleButtons();
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
new AlertDialog.Builder(this)
.setMessage(R.string.gps_network_not_enabled)
.setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton(R.string.Cancel,null)
.show();
}
else
{
//GPS is ON
GPS_ACCESS=true;
//requestWLANAccess();
}
}
public void requestWLANAccess(){
//WIFI is not ON
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
// wifi is enabled
WLAN_ACCESS=true;
}
else
{
new AlertDialog.Builder(this)
.setMessage(R.string.wifi_network_not_enabled)
.setPositiveButton(R.string.open_WIFI_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNegativeButton(R.string.Cancel,null)
.show();
}
}
#Override
protected void onResume() {
super.onResume();
//setContentView(R.layout.activity_dblogin);
requestLocationPermission();
}
private void disbaleButtons()
{
register= findViewById(R.id.register);
login= findViewById(R.id.login);
anon= findViewById(R.id.anon);
login.setEnabled(false);
register.setEnabled(false);
anon.setEnabled(false);
}
private void enableButtons()
{
register= findViewById(R.id.register);
login= findViewById(R.id.login);
anon= findViewById(R.id.anon);
login.setEnabled(true);
register.setEnabled(true);
anon.setEnabled(true);
}
private void onAccessGranted()
{
final String idDevice = Settings.Secure.getString(this.getContentResolver(),
Settings.Secure.ANDROID_ID);
sharedPreferences = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
email =findViewById(R.id.email);
password= findViewById(R.id.password);
register= findViewById(R.id.register);
login= findViewById(R.id.login);
loginState= findViewById(R.id.checkbox);
anon= findViewById(R.id.anon);
tacState= findViewById(R.id.agree);
tacAgree =findViewById(R.id.terms);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(dblogin.this, register.class));
finish();
}
});
anon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//continue as guest
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString("guestmode","anon");
editor.commit();
checkScore(idDevice);
}
});
tacAgree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(dblogin.this, agreement.class));
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tacState.isChecked()) {
// Agreed to TAC
String txtEmail =email.getText().toString();
String txtPassword =password.getText().toString();
if ( TextUtils.isEmpty(txtEmail) || TextUtils.isEmpty(txtPassword))
{
Toast.makeText(dblogin.this, "Please fill all the required fields", Toast.LENGTH_SHORT).show();
}
else
{
login(txtEmail,txtPassword);
}
}
else
{
//Please agree
Toast.makeText(dblogin.this, "Please agree to the terms and conditions of usage and privacy", Toast.LENGTH_LONG).show();
}
}
});
String loginStatus = sharedPreferences.getString(getResources().getString(R.string.prefLoginState),"");
String getEmail = sharedPreferences.getString("prefEmail","");
if(loginStatus.equals("loggedin"))
{
checkScore(getEmail);
}
else
{
//TODO what happens when logged out is the state in the shared preferences
}
}
// END OF ON CREATE METHOD
private void checkScore(final String mEmail)
{
final ProgressDialog progressDialog2 = new ProgressDialog(dblogin.this);
progressDialog2.setCancelable(false);
progressDialog2.setIndeterminate(false);
progressDialog2.setTitle("Checking Login Data");
progressDialog2.show();
String URL = "https://innosens.com.my/dboard/check.php";
StringRequest request = new StringRequest(com.android.volley.Request.Method.POST, URL, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("No Score"))
{
progressDialog2.dismiss();
saveScore("-1",mEmail.toString());
//Toast.makeText(dblogin.this, response, Toast.LENGTH_SHORT).show();
}
else
{
saveScore(response,mEmail.toString());
progressDialog2.dismiss();
//Toast.makeText(dblogin.this, response, Toast.LENGTH_LONG).show();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog2.dismiss();
Toast.makeText(dblogin.this, error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> param = new HashMap<>();
param.put("email", mEmail);
return param;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(dblogin.this).addToRequestQueue(request);
}
public void saveScore(String score, String email)
{
if ((Integer.parseInt(score))>=0) {
responseData=Integer.parseInt(score);
Intent intent = new Intent(dblogin.this, finalscore.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("SCORE", responseData);
intent.putExtra("EMAIL", email);
dblogin.this.startActivity(intent);
finish();
}
else
{
Intent intent = new Intent(dblogin.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
dblogin.this.startActivity(intent);
finish();
}
}
private void login(final String email, final String password)
{
final ProgressDialog progressDialog = new ProgressDialog(dblogin.this);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setTitle("Loggin In ");
progressDialog.show();
String URL = "https://www.innosens.com.my/dboard/login.php";
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("Login Success"))
{
progressDialog.dismiss();
//Toast.makeText(dblogin.this, response, Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = sharedPreferences.edit();
if (loginState.isChecked())
{
editor.clear();
editor.putString("prefEmail",email);
editor.putString(getResources().getString(R.string.prefLoginState),"loggedin");
editor.commit();
}
else
{
editor.clear();
editor.putString("prefEmail",email);
editor.putString(getResources().getString(R.string.prefLoginState),"loggedout");
editor.commit();
}
checkScore(email);
}
else
{
progressDialog.dismiss();
Toast.makeText(dblogin.this, response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(dblogin.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> param = new HashMap<>();
param.put("email", email);
param.put("password", password);
return param;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(dblogin.this).addToRequestQueue(request);
} // END OF METHOD LOGIN }
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 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 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 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());
}
});
}