I am new to android. I am developing an application which requires facebook login to proceed. So for this I have followed this tutorial - https://developers.facebook.com/docs/android/getting-started
EDIT: Using UILifecycleHelper, same thing happen, once user authenticates the application application is closed.
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.w("Vinit", "Session started");
// make request to the /me API
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView t = (TextView) findViewById(R.id.textView1);
t.setText("User: " + user.getFirstName());
}
}
}).executeAsync();
}
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.d("HelloFacebook", "Success!");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(new LoginChecker(this).isRegistered()){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}else{
setContentView(R.layout.activity_login);
LoginButton loginButton = (LoginButton) findViewById(R.id.loginButton1);
thisActivity = this;
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
uiHelper = new UiLifecycleHelper(thisActivity, callback);
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.w("Vinit", "On Activity Result function");
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
Use UiLifecycleHelper
https://developers.facebook.com/docs/reference/android/current/class/UiLifecycleHelper
to be sure that your activity/fragment handle processing from facebook component in proper way.
Check Facebook Session object.
Does app call instructions inside session.IsOpened()? Try debug your code to see state of the Facebook Session.
Related
So here is the code
public void redirectToMain(){
Intent intent = new Intent(getApplicationContext(), MainScreen.class);
startActivity(intent);
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pers.clear();
pers.add("user_friends");
pers.add("email");
if (ParseUser.getCurrentUser() != null) {
redirectToMain();
}
loginButton = (LoginButton) findViewById(R.id.login_button);
callbackManager = CallbackManager.Factory.create();
loginButton.setReadPermissions("email", "user_friends");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
parseLogin();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
public void parseLogin(){
loginButton.setVisibility(View.INVISIBLE);
ParseFacebookUtils.logInWithReadPermissionsInBackground(this, pers, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if(user==null){
Log.i("Cancel", "facebook");
}else if(user.isNew()){
Log.i("Parse", "succcess");
redirectToMain();
}
else{
Log.i("Parse", "old");
redirectToMain();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data );
ParseFacebookUtils.onActivityResult(requestCode,resultCode,data);
}
}
And everything works fine, the user gets redirected to the second activity, but the activity gets called twice. Also, the log part that says old is also written twice in the logcat, so my assumption is that either parseLogin() or the ParseFacebookUtils.log...() is called twice. Any idea why that is happening?
I managed to fix it by adding an int and a while loop that executes the code only once. It's more of a hack than a fix, so maybe somebody can come up with a better solution.
The facebook login is showing, I logged into facebook, confirmed the information, but when I go back to my app the AccessToken did not work. When I tested:
FacebookSdk.sdkInitialize(getApplicationContext(), new FacebookSdk.InitializeCallback() {
#Override
public void onInitialized() {
if(AccessToken.getCurrentAccessToken() == null){
System.out.println("not logged in yet");
} else {
System.out.println("Logged in");
}
}
});
the result is not logged in yet
This is the code login:
public void loginFacebook(View v){
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(UserPerfilActivity.this, "VocĂȘ Clicou em: ", Toast.LENGTH_LONG).show();
System.out.println("publish");
// sharePhotoToFacebook();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
}
});
}
But the callbackManager doesn't work, I don't have publish or cancel or error println.
Fix the problem, I added this code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode,
resultCode, data);
}
this is the post:
post stackoverflow link
After spending days trying to figure this out, I couldn't come up with anything that worked. Using my code, it shows me the permission form which I accept and log in but it doesn't get to the onSuccess, onError or onCancel. Anytime I click the button, it just doesn't do anything. And no errors on the LogCat. I don't know where i'm going wrong.
fb = (Button) findViewById(R.id.fb_button);
fb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this,permissionNeeds);
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("kkkkkk","kkllkl");
}
#Override
public void onCancel() {
Log.d("kkkkkk","kkllkl2");
}
#Override
public void onError(FacebookException error) {
Log.d("kkkkkk","kkllkl4");
}
});
}
});
The FacebookSdk.sdkInitialize(this.getApplicationContext()); is initialized after the super.onCreate(savedInstanceState);
I finally figured it out. I changed the code a bit from the initial code to this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("kkkkkk","kkllkl");
}
#Override
public void onCancel() {
Log.d("kkkkkk","kkllkl2");
}
#Override
public void onError(FacebookException error) {
Log.d("kkkkkk","kkllkl4");
}
});
and then in the button's on click listener, i just had to make the call for the login.
fb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this,permissionNeeds);
}
});
also don't forget to add the onActivityResult. I made the mistake also.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
The complete code is below.
public class MainActivity extends ActionBarActivity {
CallbackManager callbackManager;
Button but, but2;
AccessTokenTracker accessTokenTracker;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but = (Button) findViewById(R.id.button);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
// savedInstanceState
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends" ));
// }
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
}
};
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getUserData(AccessToken.getCurrentAccessToken());
Log.d("Access Token: ", AccessToken.getCurrentAccessToken().toString());
}
});
}
public void getUserData(AccessToken accessToken){
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
//JSONParser parser=new JSONParser();
// Data data = new Gson().fromJson(json, Data.class);
long ID = 0;
try {
String name = response.getRawResponse();
Toast.makeText(MainActivity.this, "response is: "+object.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "error is: "+e.toString(), Toast.LENGTH_LONG).show();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onDestroy() {
super.onDestroy();
accessTokenTracker.stopTracking();
}
}
I am a newbiew in Android. I have intergarted Facebook in my Android app. I have a Login page with a button. On click of that button the FB login page appears.After the successful login of Facebook, the user gets to go to the MainActivity. I want to hide my Login page after the successful login of FB. That is, when I reload the app, if the user has already logged in then the MainActivity only should be dispalyed and not the Login page.
My code is as follows:
public class Login extends Activity {
private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";
//private TextView textInstructionsOrLink;
private ImageButton buttonLoginLogout;
public static final String PREFS_PRIVATE = "PREFS_PRIVATE";
private Button b;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
Databasehandler db=new Databasehandler(this);
HashMap<String, String>map=new HashMap<String, String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
buttonLoginLogout = (ImageButton)findViewById(R.id.imageButton1);
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
}
}
updateView();
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Request.executeMeRequestAsync(session,new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
final String t1=user.getId();
final String t2=user.getName();
// SharedPreferences myPrefs =getSharedPreferences("myprefs",MODE_WORLD_READABLE);
int count=db.getme();
if(count==0)
{
map.put("uid",t1.toString());
map.put("name",t2.toString());
db.insertnewuser(map);
}
}
});
Intent ik=new Intent(Login.this,MainActivity.class);
ik.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(ik);
} else {
buttonLoginLogout.setOnClickListener(new OnClickListener() {
public void onClick(View view) { onClickLogin(); }
});
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
updateView();
}
}
}
Just add below code inside updateView method.
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
So your full method will look something like below code.
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Request.executeMeRequestAsync(session,new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
final String t1=user.getId();
final String t2=user.getName();
// SharedPreferences myPrefs =getSharedPreferences("myprefs",MODE_WORLD_READABLE);
int count=db.getme();
if(count==0)
{
map.put("uid",t1.toString());
map.put("name",t2.toString());
db.insertnewuser(map);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
}
}
So basically it will automatically moves to next screen whenever facebook session is opened.
//After successfull login it hide the facebook button
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
//after successful login into the facebook it hide the logout button
loginButton.setVisibility(View.GONE);
}
//if you want to logout after login to facebook successfully then you want to write this line inside the onSccess() method at the end
//after successful login into the facebook it hide the logout button
LoginManager.getInstance().logOut();
I am following this tutorial for integrating Facebook SDK for Android. It works perfectly. My problem is that what if I want to log out of the Facebook (like closing the session). How to do log in and log out on same Button.
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(this,MainActivity.class);
startActivity(i);
}
});
Following is my code:
public class MainActivity extends Activity {
private Button button1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Session.openActiveSession(this, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
// TODO Auto-generated method stub
Request.executeMeRequestAsync(session,new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
if(user!=null){
TextView tv1=(TextView)findViewById(R.id.textview1);
tv1.setText("Hello "+user.getName()+ ";");
}
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
I want to log in and log out on buttonClick. Can anyone help?
Thanks in advance.
Call this method.you will logout from the session
session.closeAndClearTokenInformation();