Facebook can't finish() - android

I have a problem. I want when I log in from my MainActivity to go to another activity, which I already did, but at the same time I don't want to be able to go back, and the logout button become in MainActivity2.
Code:
private FacebookCallback<LoginResult> mCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
Intent mainLobby = new Intent (getActivity(), MainActivity2.class);
startActivity(mainLobby);
if(!isMainLobbyStarted) {
startActivity(mainLobby);
isMainLobbyStarted = true;
Toast.makeText(getActivity().getApplicationContext(), "Bem-vindo " + profile.getName(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};

For you not to go back to activity 1, you can override the onBackPressed() on activity 2 to do nothing.
public void onBackPressed() {
//do nothing
}
Hope this helps.

Related

Initiate login activity by one click

I am working on a custom button which enable Facebook login. What I am coding gave me a result which I need to tap the button twice only it will start the activity.
I was trying to work on it through adjusting the position of startActivity() function in different way. And I found that I can make it to become initialization through placing the startActivity() function just after the finding of view for button bLogin.
Logically, it seems not right as no user will start to proceed to the next activity before login.
Any solution on this? Thank you in advance.
For your information, here are my MainActivity java code.
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
GraphRequest graphRequest;
com.facebook.login.LoginManager fbLoginManager;
Button bLogin;
#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);
}
//new activity from login page
public void chatbox (View view){
final Intent intent = new Intent(this, tabviewChatbox.class);
fbLoginManager = com.facebook.login.LoginManager.getInstance();
callbackManager = CallbackManager.Factory.create();
bLogin = (Button) findViewById(R.id.bLogin);
//only start activity if login success
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
startActivity(intent);
finish();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
}
});
}
public void graphRequest(AccessToken accessToken) {
graphRequest = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("response", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,birthday,friends");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
//Function calling for integration of font awesome, can directly put icon inside default button by typing name
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(IconicsContextWrapper.wrap(newBase));
}
}

Facebook SDK's logInWithPublishPermissions stucks with everlasting spinner

I want to ask the user of my android app the permission to publish on facebook when a custom share button (it's just an ImageView) is pressed. On button's OnClick method I execute this block:
CallbackManager facebookCallbackManager;
...
facebookCallbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(facebookCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
shareContent(activity, content, true);
}
#Override
public void onCancel() { }
#Override
public void onError(FacebookException error) { }
});
LoginManager.getInstance().logInWithPublishPermissions(activity, Collections.singletonList("publish_actions"));
And then I override:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebookCallbackManager.onActivityResult(requestCode, resultCode, data);
}
The problem is that the request never comes: an everlasting spinner wheel is presented and no callback (nor success, nor cancel, nor error) is called.
a. The user is already logged in, according to:
public static boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
b. FacebookSdk.isInitialized() is true
c. Publish permissions are not granted, according to:
private static boolean hasPublishPermissions() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null && accessToken.getPermissions().contains("publish_actions");
}
d. Other uses of FB SDK are used through the app and they are functioning.
e. I am an app admin on FB dashboard
Any idea on the problem?
Important PS:
Since Facebook's API is extremely stable, depending on the time of the day or the position of the stars, without changing code I have three possible outcomes:
As described before, an everlasting spinner wheel.
The callback fires the onCancel method without the user interaction.
It shares the content without asking for confirmation - this gave me a nice unwanted video posted on my personal FB, without me noticing :) -
PS2:
Even the classic LoginManager.getInstance().logInWithReadPermissionnow is having the same issue. It never had it before.
then you can share content without everlasting spinner
LoginManager.getInstance().registerCallback(mCallbackManagerFacebook, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
if (loginResult.getRecentlyGrantedPermissions().contains("publish_actions")) {
new shareContent(activity, content, true);
} else {
//Toast.makeText(youractivity.this, "Successfully Connected to Facebook.", Toast.LENGTH_LONG).show();
GetFacebookPublishPermissions();
}
}
#Override
public void onCancel() {
//Log.d(TAG_CANCEL, "On cancel");
LoginManager.getInstance().logOut();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(youractivity.this, "Looks like we are unable to connect to Facebook Servers.", Toast.LENGTH_LONG).show();
LoginManager.getInstance().logOut();
// Log.d(TAG_ERROR, error.toString());
}
});
and getFacebookSharepermission
public void GetFacebookPublishPermissions(){
if(LoginManager.getInstance()!=null)
{
LoginManager.getInstance().logInWithPublishPermissions(youractivity.this, Arrays.asList("publish_actions"));
}
}
Update
you can call this function like below
AccessToken token = com.facebook.AccessToken.getCurrentAccessToken();
if(token!=null)
{
if (token.getPermissions().contains("publish_actions")) {
new shareContent(activity, content, true);
}else{
GetFacebookPublishPermissions();
}
}else{
LoginManager.getInstance().logInWithReadPermissions(this,
Arrays.asList("public_profile", "email", "user_birthday"));
}
I think there is mistake for callback manager.
you declare and assign CallbackManager facebookCallbackManager;
facebookCallbackManager = CallbackManager.Factory.create();
Here you can see there is cbManager instead of facebookCallbackManager
so please double check for that.
V
LoginManager.getInstance().registerCallback(cbManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
shareContent(activity, content, true);
}
#Override
public void onCancel() { }
#Override
public void onError(FacebookException error) { }
});

Logout Facebook session and launch login Activity

I'm using a Facebook button for login in a project. This button is located in LoginActivity, once I log in, it does things right and launch me to the expected Activity.
The problem is in that activity because I have another Facebook button to log out the session. I want that once that I log out the application takes me again to Login Activity. But it does nothing, it just changes the button status.
This is the code of the activity with the button that must take me again to Login Activity.
public class Main_Menu extends AppCompatActivity {
LoginButton mFacebookButton;
CallbackManager mCallBackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_principal);
mCallBackManager = CallbackManager.Factory.create();
mFacebookButton = (LoginButton)findViewById(R.id.fb_menu_button);
mFacebookButton.registerCallback(mCallBackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
LoginManager.getInstance().logOut();
goLoginActivity();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
private void goLoginActivity() {
Intent i = new Intent(Main_Menu.this, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
}
#Override
public void onBackPressed() {
super.onBackPressed();
System.exit(0);
}
}
What can I do in order to launch the login Activity?
Greetings!
Why u create the Facebook default button again simply take the button and logout from it
//Check if user is currently logged in
if (AccessToken.getCurrentAccessToken() != null && com.facebook.Profile.getCurrentProfile() != null){
//Logged in so show the login button
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logOut();
gotoLogin();
}
});
}

Unable to login using Facebook SDK

In my app, I am trying to implement Facebook login. I have an IntroLogin Activity after splash to determine whether the user is already logged in or not. If the user is already logged in, it straight loads MainActivity. Otherwise, it asks the user to log in.
My method to determine if the user is logged in or not works well in Android 6+. However, in Android Lollipop, after user sign-in (user get's to give app authenticate to use there info in popup), the app closes. I get no FCs or any messages in log. It just closes. Even if the user restarts the app, it again prompts to login.
My IntroLogin Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro_login);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
loginButton = (Button) findViewById(R.id.login_button);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if(accessToken != null){
finish();
}
else{
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupLogin();
}
});
}
}
public void PopupLogin() {
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile"));
LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_VIEW_ONLY).registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, "onSuccess: " + loginResult);
startActivity(new Intent(IntroLogin.this, MainActivity.class));
finish();
}
#Override
public void onCancel() {
Log.d("MyApp", "Login canceled");
Snackbar snackbar = Snackbar.make(loginButton, "Login process canceled", Snackbar.LENGTH_INDEFINITE);
snackbar.getView().setBackgroundColor(ContextCompat.getColor(IntroLogin.this, R.color.colorPrimaryDark));
snackbar.setActionTextColor(ContextCompat.getColor(IntroLogin.this, R.color.pure_white));
snackbar.setAction(R.string.retry_login, new View.OnClickListener() {
#Override
public void onClick(View view) {
loginButton.performClick();
}
});
snackbar.show();
}
#Override
public void onError(FacebookException error) {
Log.d("Myapp", error.toString());
Toast.makeText(IntroLogin.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
UPDATE:
I found the cause but not the solution, I think OnActivityResult is not getting called in lollipop, that maybe the reason i am not seeing any log.
you should initialize your facebooksdk just after calling super.oncreate()
And also you are calling finish() when accessToken != null which means when user is already logged in facebook it will close the activity..
Change your onCreate() method code to:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_intro_login);
callbackManager = CallbackManager.Factory.create();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
loginButton = (Button) findViewById(R.id.login_button);
updateWithToken(AccessToken.getCurrentAccessToken());
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
updateWithToken(newToken);
}
};
accessTokenTracker.startTracking();
}
private void updateWithToken(AccessToken currentAccessToken) {
if (currentAccessToken != null) {
Log.d("FB", "User Logged IN.");
//programetically logout user or do your on success
LoginManager.getInstance().logOut();
} else {
Log.d("FB", "User Logged Out.");
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupLogin();
}
});
}
}
Found out the cause. I have added android:launchMode="singleTop" in my loginActivity, that was the reason why OnActivityResult was not calling.

Facebook login in fragment

I would like to use Facebook login in my App. I have just registred app and added SDK to project. However, I tried to follow the tutorial from documentation but nothing worked (I need to get ID and email from profile and send to to my server).
Fragment
public class LoginFragment extends Fragment {
#BindView(R.id.ivLogo) ImageView ivLogo;
#BindView(R.id.email) EditText edEmail;
#BindView(R.id.password) EditText edPassword;
#BindView(R.id.btnFbLogin) LoginButton btnFbLogin;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
String email, password, ID;
User user;
public LoginFragment() {
// Required empty public constructor
}
public static LoginFragment newInstance() {
LoginFragment fragment = new LoginFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.i("success", "success");
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login_screen, container, false);
ButterKnife.bind(this, view);
btnFbLogin.setReadPermissions("email");
btnFbLogin.setFragment(this);
// Callback registration
btnFbLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
((MainActivity) getActivity()).getSupportActionBar().hide();
}
private void FBcallback() {
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
String email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onCancel() { }
#Override
public void onError(FacebookException e) { }
};
btnFbLogin.setReadPermissions("email");
btnFbLogin.registerCallback(callbackManager, callback);
}
private void loginEmail() {
FactoryAPI.getInstanceLogin().login("hardcoded mail", "hardcoded password").enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
user = response.body().getUser();
startActivity();
} else {
Toast.makeText(getContext(), R.string.email_password_is_not_right, Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
}
});
}
private void loginFB() {
FactoryAPI.getServieFBlogin().loginFB(email, ID).enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
user = response.body().getUser();
startActivity();
} else {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
Log.e("error", "error");
}
});
}
public void getEmailPassword() {
email = edEmail.getText().toString();
password = edPassword.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(getContext(), R.string.empty_properties, Toast.LENGTH_SHORT).show();
}
}
public static boolean emailValidation(CharSequence target) {
return !TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public void startActivity() {
Intent intent = new Intent(getContext(), AccountActivity.class);
intent.putExtra("account", user);
startActivity(intent);
}
#Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
#OnClick({R.id.sign_up_email, R.id.btnFbLogin})
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_up_email:
loginEmail();
case R.id.btnFbLogin:
break;
}
}
private void getProfile(Profile profile){
if(profile != null){
ID = profile.getId();
}
}
}
As your facebook login is in Fragment not in activity, so the
callback comes in onActivityResult() of Activity in which this fragment attached.
You can check this after override the onActivityResult() of your activity, and put a debug point there.
After you getting result in your activity onActivityResult() method, you can send it to your fragment's onActivityResult().
Hope this will help.
First of all if you are using LoginButton then you don't need to register with LoginManager. Here is the sample
//Using Facebook's LoginButton
//Register Callback
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email")); //set permissions as public_profile, email, etc
loginButton.setFragment(this); //If you are using in a fragment
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
Now with LoginManager when using Custom Button to login instead of FB's LoginButton
//To check if you are already logged In
boolean loggedIn = AccessToken.getCurrentAccessToken() == null;
// To Manually login. This will launch facebook's login screen.
LoginManager.getInstance().logInWithReadPermissions(this,
Arrays.asList("public_profile","email"));
In both the cases, for Fragment or Activity you need to handle onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}

Categories

Resources