0

I have a facebook login option in my android application.

When there is no Facebook application installed on my device, this login works fine. But when the facebook application is installed, it creates problems in a few cases.

So, how can I tell my application's facebook login to ignore if Facebook app is installed and proceed in the previous way (assuming facebook application is not installed)?

This is the activity called when i click the fbLoginButton:

public class Example extends Activity {

    public static final String APP_ID = myAppIdHere;


    private LoginButton mLoginButton;
    private TextView mText;
    private Button mRequestButton;
    private Button mPostButton;
    private Button mDeleteButton;
    private Button mUploadButton;
    public static Activity ExampleActivity;

    private Facebook mFacebook;
    private AsyncFacebookRunner mAsyncRunner;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ExampleActivity = this;
        if (APP_ID == null) {
            Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " +
                    "specified before running this example: see Example.java");
        }

       setContentView(R.layout.facebook);
        mLoginButton = (LoginButton) findViewById(R.id.login);
        mFacebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(mFacebook);

        SessionStore.restore(mFacebook, this);
        SessionEvents.addAuthListener(new SampleAuthListener());
        SessionEvents.addLogoutListener(new SampleLogoutListener());
        mLoginButton.init(this, mFacebook);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {

        mFacebook.authorizeCallback(requestCode, resultCode, data);
    }

    public class SampleAuthListener implements AuthListener {

        public void onAuthSucceed() {

        }

        public void onAuthFail(String error) {

        }
    }

    public class SampleLogoutListener implements LogoutListener {
        public void onLogoutBegin() {

        }

        public void onLogoutFinish() {

    }
}

This is LoginButton Class:

public class LoginButton extends ImageButton {

    public static Facebook mFb;
    public static String facebookID;
    public static String firstName;
    public static String lastName;
    public static String email = "";
    public static String sex;
    private Handler mHandler;
    private SessionListener mSessionListener = new SessionListener();
    private String[] mPermissions = new String[] { "read_stream", "email" };
    private Activity mActivity;

    public LoginButton(Context context) {
        super(context);
    }

    public LoginButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LoginButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void init(final Activity activity, final Facebook fb) {
        init(activity, fb, new String[] {});
    }

    public void init(final Activity activity, final Facebook fb,
            final String[] permissions) {
        mActivity = activity;
        mFb = fb;
        mPermissions = new String[] { "read_stream", "email" };
        ;
        mHandler = new Handler();

        setBackgroundColor(Color.TRANSPARENT);
        setAdjustViewBounds(true);

        if(mFb.isSessionValid()){
            getUser();
            SessionEvents.onLogoutBegin();
            AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb);
            asyncRunner.logout(getContext(), new LogoutRequestListener());
        }else{

            setImageResource(R.drawable.login_button);
            drawableStateChanged();
        }

        SessionEvents.addAuthListener(mSessionListener);
        SessionEvents.addLogoutListener(mSessionListener);
        setOnClickListener(new ButtonOnClickListener());
    }

    private final class ButtonOnClickListener implements OnClickListener {

        public void onClick(View arg0) {
            if (mFb.isSessionValid()) {
                getUser();
                SessionEvents.onLogoutBegin();
                AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb);
                asyncRunner.logout(getContext(), new LogoutRequestListener());
            } else {
                mFb.authorize(mActivity, mPermissions,
                        new LoginDialogListener());
            }
        }
    }

    private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {

            SessionEvents.onLoginSuccess();
        }

        public void onFacebookError(FacebookError error) {

            SessionEvents.onLoginError(error.getMessage());
        }

        public void onError(DialogError error) {

            SessionEvents.onLoginError(error.getMessage());
        }

        public void onCancel() {

            SessionEvents.onLoginError("Action Canceled");
        }

    }

    private class LogoutRequestListener extends BaseRequestListener {
        public void onComplete(String response, final Object state) {

            mHandler.post(new Runnable() {
                public void run() {

                SessionEvents.onLogoutFinish();
                }
            });
        }
    }

    private class SessionListener implements AuthListener, LogoutListener {

        public void onAuthSucceed() {

            setImageResource(R.drawable.logout_button);
            SessionStore.save(mFb, getContext());
        }

        public void onAuthFail(String error) {
        }

        public void onLogoutBegin() {
        }

        public void onLogoutFinish() {

            SessionStore.clear(getContext());
            setImageResource(R.drawable.login_button);
        }
    }

    public static void getUser() {

        try {
            JSONObject json = Util.parseJson(mFb.request("me"));
            facebookID = json.getString("id");
            firstName = json.getString("first_name");
            lastName = json.getString("last_name");
            email = json.getString("email");
            sex = json.getString("gender");
            String mFirstName = firstName;
            String mLastName = lastName;
            String mEmail = email;
            String mSex = sex;
            Log.d("User Details", "You are logged in : " + facebookID
                    + mFirstName + "." + mLastName + "  Email is: " + mEmail
                    + "-" + mSex);

            SharedPreferences.Editor editor = SignUpActivity.settings.edit();

            // Set "hasLoggedIn" to true
            editor.putBoolean("hasLoggedIn", true);
            editor.putString("fbEmail", email);
            editor.putString("fbId", facebookID);
            editor.putString("fbSex", sex);
            editor.putString("fbFirstname", firstName);
            editor.putString("fbLastname", lastName);

            // Commit the edits!
            editor.commit();
        } catch (Exception e) {
            // TODO: handle exception
            Log.d("Exception in getUser", "+++++" + e.toString());
        }
    }
}

This is SessionEvents Class:

public class SessionEvents {

    private static LinkedList<AuthListener> mAuthListeners = new LinkedList<AuthListener>();
    private static LinkedList<LogoutListener> mLogoutListeners = new LinkedList<LogoutListener>();

    public static void addAuthListener(AuthListener listener) {

        mAuthListeners.add(listener);
    }

    public static void removeAuthListener(AuthListener listener) {

        mAuthListeners.remove(listener);
    }

    public static void addLogoutListener(LogoutListener listener) {

        mLogoutListeners.add(listener);
    }

    public static void removeLogoutListener(LogoutListener listener) {

        mLogoutListeners.remove(listener);
    }

    public static void onLoginSuccess() {

        LoginButton.getUser();
        for (AuthListener listener : mAuthListeners) {
            listener.onAuthSucceed();
        }
    }

    public static void onLoginError(String error) {

        for (AuthListener listener : mAuthListeners) {
            listener.onAuthFail(error);
        }
    }

    public static void onLogoutBegin() {

        for (LogoutListener l : mLogoutListeners) {
            l.onLogoutBegin();
        }
    }

    public static void onLogoutFinish() {

        for (LogoutListener l : mLogoutListeners) {
            l.onLogoutFinish();
        }
    }

    public static interface AuthListener {

        public void onAuthSucceed();

        public void onAuthFail(String error);
    }

    public static interface LogoutListener {

        public void onLogoutBegin();

        public void onLogoutFinish();
    }

}

This is SessionStore class:

public class SessionStore extends Activity{

    private static final String TOKEN = "access_token";
    private static final String EXPIRES = "expires_in";
    private static final String KEY = "facebook-session";

    public static boolean save(Facebook session, Context context) {

        Context contextObj = Example.ExampleActivity;
        Intent i=new Intent(contextObj , SignUpActivity.class);
        contextObj.startActivity(i);

        Editor editor =
            context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
        editor.putString(TOKEN, session.getAccessToken());
        editor.putLong(EXPIRES, session.getAccessExpires());
        return editor.commit();
    }

    public static boolean restore(Facebook session, Context context) {

        SharedPreferences savedSession =
            context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
        session.setAccessToken(savedSession.getString(TOKEN, null));
        session.setAccessExpires(savedSession.getLong(EXPIRES, 0));
        return session.isSessionValid();
    }

    public static void clear(Context context) {

        Editor editor = 
            context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
        editor.clear();
        editor.commit();
    }

}

This is BaseRequestListener class:

public abstract class BaseRequestListener implements RequestListener {

    public void onFacebookError(FacebookError e, final Object state) {
        Log.e("Facebook", e.getMessage());
        e.printStackTrace();
    }

    public void onFileNotFoundException(FileNotFoundException e,
            final Object state) {
        Log.e("Facebook", e.getMessage());
        e.printStackTrace();
    }

    public void onIOException(IOException e, final Object state) {
        Log.e("Facebook", e.getMessage());
        e.printStackTrace();
    }

    public void onMalformedURLException(MalformedURLException e,
            final Object state) {
        Log.e("Facebook", e.getMessage());
        e.printStackTrace();
    }
}
Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
  • 1
    Surely it would be better to fix the problem than avoid it? What is happening when the Facebook application is installed? – Rawkode Jul 02 '12 at 12:40
  • when i click on the facebook login button in my app...it takes me to a fbLoginButton...on clicking this takes me to the Facebook application login screen (if fb app is installed, else will take to a dialog)....when i enter my fb credentials and hit go...it asks for permission to allow the application use my info, i click okay...then it takes me back to the fbLoginButton....i again click on it and do the same process again and again...after some 3rd or 4th try it logs into my application....so whats wrong till then? – Archie.bpgc Jul 02 '12 at 12:44
  • if u want i can paste code and images – Archie.bpgc Jul 02 '12 at 12:44
  • Update question with some code and I'll take a look – Rawkode Jul 02 '12 at 12:45
  • yeah pasted all the code i am using – Archie.bpgc Jul 02 '12 at 12:58
  • see the [link][1], I have provided answer in this page [1]: http://stackoverflow.com/questions/7712361/android-single-sign-on/7820321#7820321 – Maulik J Jul 02 '12 at 13:10
  • See the below link http://stackoverflow.com/questions/7712361/android-single-sign-on/7820321#7820321 – Maulik J Jul 02 '12 at 13:11

1 Answers1

2

Please update below code of your Login Button Click listener.

mFb.authorize(mActivity, mPermissions, Facebook.FORCE_DIALOG_AUTH,
            new LoginDialogListener());

instead of

mFb.authorize(mActivity, mPermissions, new LoginDialogListener());

And see below link for more information

Facebook Login Issue

Community
  • 1
  • 1
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
  • actually i dont want to post on wall and all that stuff....i just want to get the user details from the credentials he/she enters – Archie.bpgc Jul 02 '12 at 13:10
  • yeah i used your code, it shows the dialog(case when fb app is not installed) instead of fb app login screen. but the result is same. and this is obvious because, only the login dialog changes but the rest it uses fb application's right?? – Archie.bpgc Jul 02 '12 at 13:30
  • above solution is working for me, if facebook application is installed in your device at that time also log in dialog is open. – Dipak Keshariya Jul 03 '12 at 04:36
  • yeah Log in Dialog opens (not the Facebook Login)...but when i enter the login credentials and submit it takes me back to the Log in Dialog, when i use log cat i found out that my flow ends in onActivityResult of the Example Activity....please help – Archie.bpgc Jul 03 '12 at 05:01
  • after successful login what is the next step of your application? – Dipak Keshariya Jul 03 '12 at 05:03
  • should paste where all my flow goes...using logcat?? – Archie.bpgc Jul 03 '12 at 05:15
  • onCreate in Example --> restore inSessionStore --> addAuthListener in SessionEvents --> addLogoutListener in SessionEvents --> init in LoginButton class --> addAuthListener in SessionEvents --> addLogoutListener in SessionEvents --> else block of BUttonOnCliclListener in LoginButton class --> onCreate in Example --> restore inSessionStore --> addAuthListener in SessionEvents --> addLogoutListener in SessionEvents --> init in LoginButton class --> addAuthListener in SessionEvents --> addLogoutListener in SessionEvents --> onActivityResult in Example activity – Archie.bpgc Jul 03 '12 at 05:19
  • these are the logs i get in log cat.....i added log to every method and block....the 1st onCreate in Example is the one i get when i click on the LoginButton to open the dialog....and finally i end up at the same LoginButton showing onAvtivityResult in the logcat – Archie.bpgc Jul 03 '12 at 05:21
  • Actually this problem occurs when....Facebook application is installed on the device but the user is *not logged in*. If he is logged in, its working fine – Archie.bpgc Jul 03 '12 at 07:04
  • when i am not logged into my facebook application,....in my android application i login from the Login Dialog then it takes me back to Login dialog, once again i click Login in the Dialog now it takes me to my application fbLoginButton, again i click login, this time it works (it takes me to my application with these credentials). – Archie.bpgc Jul 03 '12 at 07:06
  • @Archie.bpgc sorry for that but i don't know about this. – Dipak Keshariya Jul 03 '12 at 07:08