I have followed some tutorials how to use facebook with android app. I managed to implement working "log in" button and "share" button however I cant make like button work properly. After I press it i get this question image appearing for a second and then it disapears:
Here is my application code(its simple activity with fragment in it):
public class FacebookFragment extends Fragment {
private View rootView;
private TextView simpleTextView;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//PODSTAWOWE RZECZY
FacebookSdk.sdkInitialize(getActivity().getApplicationContext()); //facebook
callbackManager = CallbackManager.Factory.create();
registerCallback();
//JAKIEŚ TOKENY I INNE TRACKERY DO UPDATÓW
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
Toast.makeText(getActivity().getApplicationContext(), "currentAccessTokenChanged", Toast.LENGTH_LONG).show();
simpleTextView.setText("current access token changed");
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
// App code
if (currentProfile != null) {
((TextView) rootView.findViewById(R.id.textView)).setText("Welcome " + currentProfile.getName());
} else {
Toast.makeText(getActivity().getApplicationContext(), "Profil null", Toast.LENGTH_LONG).show();
}
}
};
//ZACZYNAMY ŚLEDZIĆ
profileTracker.startTracking();
accessTokenTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_facebook, container, false);
//SPRAWDZAMY CZY ZALOGOWANY JEST UZYTKOWNIK I ROBIMY SET-UP PROGRAMU
simpleTextView = (TextView) rootView.findViewById(R.id.textView);
checkIfLogged();
setFacebookLoginButton();
setFacebookLikeButton();
setFacebookShareButton();
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onStop() {
super.onStop();
//STOPUJEMY TRACKING
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//========================= CUSTOM METHODS ========================================
private void checkIfLogged(){
Profile profile = Profile.getCurrentProfile();
if (AccessToken.getCurrentAccessToken() != null) {
simpleTextView.setText("Welcome " + profile.getName());
} else {
Toast.makeText(getActivity().getApplicationContext(), "not logged in", Toast.LENGTH_LONG).show();
}
}
private void setFacebookLoginButton(){
LoginButton facebookButton = (LoginButton) rootView.findViewById(R.id.login_button);
facebookButton.setFragment(this);
}
private void registerCallback(){
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
}
#Override
public void onCancel() {
Toast.makeText(getActivity().getApplicationContext(), "too bad you didn't log in...", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException exception) {
Toast.makeText(getActivity().getApplicationContext(), "that's that error shit...", Toast.LENGTH_LONG).show();
}
});
}
private void setFacebookLikeButton(){
LikeView likeView = (LikeView) rootView.findViewById(R.id.like_button);
likeView.setLikeViewStyle(LikeView.Style.STANDARD);
likeView.setFragment(this);
likeView.setOnErrorListener(new LikeView.OnErrorListener() {
#Override
public void onError(FacebookException e) {
Toast.makeText(getActivity().getApplicationContext(), "masz chuja nie lajka...", Toast.LENGTH_LONG).show();
}
});
likeView.setObjectIdAndType("https://www.facebook.com/FacebookDevelopers", LikeView.ObjectType.PAGE);
}
private void setFacebookShareButton(){
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse("http://joemonster.org"))
.setImageUrl(Uri.parse("http://joemonster.org/i/2015/05/pasazer.jpg")).
setContentDescription("Prawdopodobnie najlepsza strona we wszechświecie!")
.setContentTitle("Joe Monster")
.build();
ShareButton shareButton = (ShareButton)rootView.findViewById(R.id.share_button);
shareButton.setFragment(this);
shareButton.setShareContent(content);
}
}
Other concerning behaviour:
If I use "share" button to log in then my "log in" button doesn't change to display "Log out". If I then click "log in" button and cancel it. I will have to "log in" again with "share" or "like" button.
If I use "log in" button to log in then below like button I see number of likes this site get.
I don't have facebook app installed in my virtual device.
Use of the Like button requires app approval, so during development, only users with Admin/Developer/Tester roles in your app can access it. Once it's approved, then any user can use the feature.
Related
I integrated facebook login to my Android App. I was able to login when I launch the Application, but when I logout and come back to initial screen to login again ,it does not login I was taken to Home screen of mobile . But when I relaunch the app again from launcher and try to login, I am able to login.But with in the App , when I try to relogin it does not login.
For information , I used custom button to login into facebook.
The below is the code :
Fragment and OnCreate() Method
public class SocialFragment extends Fragment implements View.OnClickListener {
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private CallbackManager callbackManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeFaceBook();
}
//Initilization of Facebook SDK
private void initializeFaceBook(){
Log.d(TAG,"initializeFacebook.......");
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
Log.d(TAG,"onCurrentAccessTokenChanged()");
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
//displayMessage(newProfile);
Log.d(TAG,"onCurrentProfileChanged()");
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
//Custom Button Click to login Facebook
private void fbLogin(){
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
}
//OnCreateView() method that contains Layout
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_social, container, false);
mContainerId = container.getId();
ImageButton fBook = (ImageButton)view.findViewById(R.id.fbook);
fBook.setOnClickListener(this);
return view;
}
//OnClickMethod()
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.fbook:
fbLogin();
//onFblogin();
break;
}
}
//OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//On Destroy
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "In onDestroy().........");
profileTracker.stopTracking();
accessTokenTracker.stopTracking();
}
//Launch New Fragment
private void displayMessage(Profile profile){
if(profile != null){
Log.d("PROFILE", profile.getName());
Toast.makeText(getActivity(), "Facebook Profile Name:::" + profile.getName(), Toast.LENGTH_LONG).show();
getFragmentManager().beginTransaction().replace(mContainerId,new BikePoolerMapFragment()).commit();
}
}
//OnResume()
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
}
Logout used in another Fragment:
LoginManager.getInstance().logOut();
Can anyone help me is relogin the facebook with in app.
Is there a way in which to logout facebook other than the way I used.
Facebook SDK used : 4.8.2
Android Studio is used
i had the same problem and the solution in my case was to make sure that the instance of the CallbackManager is the right one.
the singleton that manages the facebook had the wrong instance of the CallbackManager, therefor the callback wasn't fired.
hope it helps.
using Android Studio with SDK 4.8.2
When I'm connected by the facebook login button, I launch a custom dialog (in the onSuccess) and I want to write in this dialog the name of the person connected. It works when I do it in the layout called in onCreate(I make appear the name after connexion). But it doesn't work when I want to write this in the layout called by the dialog after the connexion (but it's the same activity).
Here is my code :
private CallbackManager mCallbackManager2;
private ProfileTracker mProfileTracker2;
private LoginButton loginbutton2;
final Context context = this;
private ProfilePictureView fAvatar2;
private TextView fName2;
private FacebookCallback<LoginResult> mCallback2 = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
/*
LAUNCH DIALOG ABOUT FACEBOOK CONNEXION
*/
// custom dialog
final Dialog dialogFacebookConnexion = new Dialog(context);
dialogFacebookConnexion.setContentView(R.layout.dialog_facebook_connect);
Button dialogButton = (Button) dialogFacebookConnexion.findViewById(R.id.dialogOk);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogFacebookConnexion.dismiss();
Intent intentmainpage = new Intent(InfoAccountActivity.this, MainPageActivity.class);
startActivity(intentmainpage);
}
});
dialogFacebookConnexion.setCanceledOnTouchOutside(false);
int dialogHeight = (int) getResources().getDimension(R.dimen.dialog_height);
int dialogWidth = (int) getResources().getDimension(R.dimen.dialog_width);
dialogFacebookConnexion.getWindow().setLayout(dialogWidth, dialogHeight);
dialogFacebookConnexion.show();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_info_account);
mCallbackManager2 = CallbackManager.Factory.create();
loginbutton2 = (LoginButton) findViewById(R.id.login_button2);
loginbutton2.setBackgroundResource(R.drawable.facebookconnexion);
loginbutton2.setReadPermissions("user_friends");
loginbutton2.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
loginbutton2.registerCallback(mCallbackManager2, mCallback2);
fName2 = (TextView) findViewById(R.id.facebookName2);
fAvatar2 = (ProfilePictureView) findViewById(R.id.facebook_avatar2);
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
OnProfileChanged(newProfile);
}
};
}
private void OnProfileChanged (Profile profile) {
if (profile != null) {
try {
fName2.setText(profile.getName());
fAvatar2.setProfileId(profile.getId());
} catch (Exception ex) {
}
} else {
}
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
OnProfileChanged(profile);
}
#Override
public void onStop() {
super.onStop();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager2.onActivityResult(requestCode, resultCode, data);
}
Is it a problem with private or protected ? An information can't be access by the dialog?
In any activity, you can use the following facebook code from their SDK once you have signed into Facebook:
Profile.getCurrentProfile().getName()
Did you try using the Request.newMeRequest using your active open session? It is easy to capture the logged user's profile afterwards.
GraphRequest rq = GraphRequest.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(final GraphUser user, Response response) { ...
...
rq.executeAndWait();
You can retrieve the user's name by user.getName() in the onCompleted method and use it anywhere.
I am new to Adroid app development and started learning for about a week.
But since 3 days i am struggling with switching the activity after successful facebook login.
My questions :
1) I need to redirect to my another activity once the user is logged in.
2) I need to have their profile details like profile picture, email and name etc on the next activity frame (which will come after login).
Current State : After login, fragment stays as it is and Logout button is displayed.
My code for the fragment here :
public class LoginFragment extends Fragment {
private CallbackManager mCallbackManager;
public AccessTokenTracker mAccessTokenTracker;
public ProfileTracker mProfileTracker;
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accesstoken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
Log.d("get me profile", "Name");
//Log.d("Welcome :", profile.getName());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public LoginFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
AccessTokenTracker mAccessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldtracker, AccessToken newtracker) {
}
};
mAccessTokenTracker.startTracking();
ProfileTracker mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldprofile, Profile newprofile) {
//Log.d("New Name", "data");
}
};
mProfileTracker.startTracking();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.login_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile");
loginButton.setFragment(this);
loginButton.registerCallback(mCallbackManager, mCallback);
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onDestroy() {
super.onDestroy();
mAccessTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Request your kind words guys to make this work.
For Answering your first question
1) In the FacebookCallback:onSuccess method you will can the method which will opens the next Activity needed, and in the onCreate of the Fragment, you will check if the AccessToken is Null, if it is null then do nothing to wait for User to press login, if it is not Null, then call the same method get open the Activity needed as the user is already logged in
2) you have check the Documents and permissions to get the Profile picture and name for the current logged user, and if you have questions, please write the code you use first to get User data
so i created a simple facebook login app following the exact instructions from this video: https://www.youtube.com/watch?v=myWu-q8Q2NA&list=PLonJJ3BVjZW4E1wIRZvuXhbFRGWB1grmh
anyways i am able to sign in but unlike the video, when I sign in, I appear back at the login page, the login button does not change to the logout button,
I click the login button, enter my login details, hit send, then a message says: You have already authorized "LoginExample (app name)". Then I appear back at the login with facebook button.
and on a similar note, I am trying to get a TextView to display a "Welcome", however it does not work, it only works when I do ' android:text="Welcome" '.
Below is my code in a fragment, I do setContentView(activity_fragment); in MainActivity. Again, the Login button appears but the TextView does not.
What is going wrong?
public class MainFragment extends Fragment {
public TextView mTextDetails;
private AccessTokenTracker mtokentracker;
private ProfileTracker mprofiletracker;
CallbackManager mCallBackManager;
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
//TextView mTextDetails = (TextView)getView().findViewById(R.id.textView);
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome " + profile.getName());
}
//setContentView(R.layout.activity_main);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainFragment() {
//TextView mTextDetails = (TextView) getView().findViewById(R.id.textView);
//mTextDetails.setText("Welcome");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallBackManager = CallbackManager.Factory.create();
AccessTokenTracker tracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken old, AccessToken niw) {
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("welcome " + profile.getName());
}
}
};
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile old, Profile niw) {
}
};
mtokentracker.startTracking();
mprofiletracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton)view.findViewById(R.id.login_button);
//loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(mCallBackManager, mCallBack);
TextView mTextDetails = (TextView)getView().findViewById(R.id.textView);
mTextDetails.setText("Welcome");
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome " + profile.getName());
}
}
#Override
public void onStop() {
super.onStop();
mtokentracker.stopTracking();
mprofiletracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallBackManager.onActivityResult(requestCode,resultCode,data);
}
}
I've started an app which has Facebook login. So I integrated facebook sdk and done the following things.
Activity.java
public class StartActivity extends FragmentActivity {
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
setContentView(R.layout.activity_start);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, new LoginFragment())
.commit();
}
}
}
LoginFragment.java
public class LoginFragment extends Fragment implements View.OnClickListener {
private EditText et_userName, et_passWord;
private Button btn_login, btn_register, btn_fb;
private LoginButton loginButton;
private CallbackManager callbackManager;
View rootView;
Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity());
callbackManager = CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.login_fragment, container, false);
et_userName = (EditText) rootView.findViewById(R.id.userName);
et_passWord = (EditText) rootView.findViewById(R.id.passWord);
btn_login = (Button) rootView.findViewById(R.id.loginButton);
btn_register = (Button) rootView.findViewById(R.id.registerButton);
loginButton = (LoginButton) rootView.findViewById(R.id.login_button);
btn_login.setOnClickListener(this);
btn_register.setOnClickListener(this);
mContext = getActivity();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(mContext, "User ID: " + loginResult.getAccessToken().getUserId() + "\n" + "Auth Token: "
+ loginResult.getAccessToken().getToken(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
Toast.makeText(mContext, "Attempt Cancelled", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
Toast.makeText(mContext, "Attempt Failed", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginButton:
Toast.makeText(getActivity(), "LOGIN", Toast.LENGTH_SHORT).show();
break;
case R.id.registerButton:
Toast.makeText(getActivity(), "REGISTER", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
}
when I click the LoginButton, Facebook login page is opened and ask for authorization, but after I press ok nothing happens just go back to fragment page.
This exact thing worked(userId and AccessToken as Toast and changing loginbutton to Logout) when I used an Activity. I used same logic in the fragment.
What went wrong??Help
In your Activity that contains the Fragment, do this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
fragment.onActivityResult(requestCode, resultCode, data);
}
If you don't have a reference to your Fragment, you can get it using
getSupportFragmentManager().findFragmentById(<container-res-id>);