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);
}
});
}
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)
Hi friends please help me out i am making chating app with the conversion of text and images Whenever user changes the image in his profile it need to be update in the conversion as well but its not getting updated but whenever i sends a new message then the new image is updating and also i dont set the primary key
Here is below link i had tried nothing worked:
How to update the values in Table using Realm android?
Update mutiple rows in table using Realm in Android
public class Chat_history extends AppCompatActivity {
#BindView(R.id.chat_history_toolbar)
CustomToolbar chat_history_toolbar;
#BindView(R.id.sendmessgae)
CustomEditText sendmessgae;
#BindView(R.id.chat_history_list)
ListView chat_history_list;
Chat_history_Adapter chathisadapter;
RealmResults<Chat_history_pojo> chathistorylist;
Realm chatrealm;
BroadcastReceiver chatreceiver;
public static final String BroadCastAction = "com.parallelspace.parallelspace.Chat_history";
RealmChangeListener chatupdatelisterner = new RealmChangeListener() {
#Override
public void onChange(Object element) {
chathisadapter.addmessage(chathistorylist);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_history);
ButterKnife.bind(this);
Realm.init(getApplicationContext());
setSupportActionBar(chat_history_toolbar);
assert getSupportActionBar() != null;
**chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
RealmQuery<Chat_history_pojo> getLoginData= chatrealm.where(Chat_history_pojo.class).beginGroup().equalTo("receiverid", getIntent().getStringExtra("rid")).endGroup();
RealmResults<Chat_history_pojo> registrationRealm = getLoginData.findAll();
for (Chat_history_pojo chtapojo:registrationRealm) {
chtapojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.copyToRealm(registrationRealm);
}
chatrealm.commitTransaction();**
chathistorylist = chatrealm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
chathisadapter = new Chat_history_Adapter(Chat_history.this, chathistorylist);
chat_history_list.setStackFromBottom(true);
chat_history_list.setTranscriptMode(chat_history_list.TRANSCRIPT_MODE_NORMAL);
chat_history_list.setAdapter(chathisadapter);
/*chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Constant.l("Realm Update Called");
RealmResults<Chat_history_pojo> updatehispojo = chatrealm.where(Chat_history_pojo.class).equalTo("receiverid", getIntent().getStringExtra("rid")).findAll();
for(Chat_history_pojo updatepojo:updatehispojo){
updatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.insertOrUpdate(updatepojo);
chathisadapter.notifyDataSetChanged();
}
}
});*/
sendmessgae.setDrawableClickListener(new DrawableClickListener() {
#Override
public void onClick(DrawablePosition target) {
switch (target) {
case RIGHT:
if (sendmessgae.getText().toString().isEmpty()) {
Constant.t(getApplicationContext(), "Please Enter Message");
} else {
sendmessage();
}
break;
default:
break;
}
}
});
if (getIntent().hasExtra("mtype")) {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
} else {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
}
chat_history_toolbar.Whichonclicked("back", new View.OnClickListener() {
#Override
public void onClick(View view) {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
});
chat_history_toolbar.Whichonclicked("toolbar", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chathisintent = new Intent(getApplicationContext(), Detailed_friend.class);
chathisintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
chathisintent.putExtra("rname", getIntent().getStringExtra("rname"));
chathisintent.putExtra("rimage", getIntent().getStringExtra("rimage"));
chathisintent.putExtra("rid", getIntent().getStringExtra("rid"));
startActivity(chathisintent);
}
});
chat_history_toolbar.Whichonclicked("delete", new View.OnClickListener() {
#Override
public void onClick(View v) {
chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Chat_history_pojo> deleteresults = realm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
deleteresults.deleteAllFromRealm();
}
});
}
});
chatreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(getIntent().getStringExtra("rid"));
chatupdatepojo.setReceiverid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(intent.getStringExtra("msg").replace("$", " "));
chatupdatepojo.setType("text");
if (intent.getStringExtra("type").equals("image")) {
chatupdatepojo.setType("image");
} else if (intent.getStringExtra("type").equals("text")) {
chatupdatepojo.setType("text");
}
chatrealm.commitTransaction();
chatrealm.close();
}
};
IntentFilter intfil = new IntentFilter(BroadCastAction);
registerReceiver(chatreceiver, intfil);
}
#Override
protected void onDestroy() {
unregisterReceiver(chatreceiver);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
chatrealm.addChangeListener(chatupdatelisterner);
Session.pushnotification(getApplicationContext());
}
#Override
protected void onStop() {
super.onStop();
chatrealm.removeChangeListener(chatupdatelisterner);
Session.removepushnotification(getApplicationContext());
}
#OnClick(R.id.camera)
public void camera() {
TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(Chat_history.this)
.setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
#Override
public void onImageSelected(Uri uri) {
try {
Bitmap sendimage = MediaStore.Images.Media.getBitmap(Chat_history.this.getContentResolver(), uri);
sendimages(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("rid"), sendimage);
} catch (IOException e) {
Constant.l(e.toString());
}
}
})
.setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
.create();
bottomSheetDialogFragment.show(getSupportFragmentManager());
}
private void sendimages(String sid, String rid, Bitmap sendbitmap) {
Constant.showloader(Chat_history.this);
String sendumageurl = Constant.psurl + "chatdocument&task=send&sender_id=" + sid + "&reciever_id=" + rid;
Constant.l(sendumageurl);
AndroidNetworking.post(sendumageurl).addBodyParameter("image", Constant.getStringImage(sendbitmap)).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
Constant.l(String.valueOf(response));
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(response.getString("url"));
chatupdatepojo.setType("image");
chatrealm.commitTransaction();
chatrealm.close();
}
} catch (JSONException e) {
Constant.l(e.toString());
Constant.dismissloader();
}
Constant.dismissloader();
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
Constant.dismissloader();
}
});
}
#Override
public void onBackPressed() {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
private void sendmessage() {
String schatsendmesg = Constant.psurl + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("rid") + "&message=" + sendmessgae.getText().toString().replace(" ", "$");
Constant.l(schatsendmesg);
AndroidNetworking.get(schatsendmesg).setOkHttpClient(Constant.okClient()).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setMessage(sendmessgae.getText().toString());
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setType("text");
chatrealm.commitTransaction();
chatrealm.close();
sendmessgae.setText("");
}
} catch (JSONException e) {
Constant.l(e.toString());
}
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
}
});
}
#Override
protected void onResume() {
super.onResume();
Session.pushnotification(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
Session.removepushnotification(getApplicationContext());
}
}
Try this way of updation.
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//Here i am checking the condition
RealmQuery<RegistrationRealm> getLoginData= realm.where(RegistrationRealm.class).equalTo("id",1);
//finding the first set if matches the criteria
RegistrationRealm registrationRealm = getLoginData.findFirst();
//setting the values
registrationRealm.setFirstname(firstname);
registrationRealm.setLastname(lastname);
//Updating the same object with new values
realm.copyToRealm(registrationRealm);
//commiting the current transaction
realm.commitTransaction();
If you need to update all, then get a RealmResults object and iterate through
RealmResults<RegistrationRealm> registrationRealm = getLoginData.findAll();
NOTE:
When using realm.copyToRealm() it is important to remember that only the returned object is managed by Realm, so any further changes to the original object will not be persisted.
Realm reference
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 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();
}
});
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());
}
});
}