Facebook SDK 3.0 Logout Not Working in android Application from any other Intent

676 views Asked by At

I am using Facebook login in android app,Its Login Successfully .

after Successful login intent goes to next page.

from Second page i am trying to logout the Facebook ,its not Working

Help me to resolve it.

else suggest me Working example for Facebook Login,logout,Getting profile information Latest SDK4.2.

Link I have used

My Logout method

public void logoutFromFacebook() {
        mAsyncRunner.logout(this, new RequestListener() {
            @Override
            public void onComplete(String response, Object state)
            {
                Log.d("Logout from Facebook", response);
                if (Boolean.parseBoolean(response) == true) 
                {


                    //Logout Successss
                }
            }

        });
    }

This My Facebook Login Code

AndroidFacebookConnectActivity.java

public class AndroidFacebookConnectActivity extends Activity {

    // Your Facebook APP ID
    private static String APP_ID = "*************" ; // Replace with your App ID

    // Instance of Facebook Class
    private Facebook facebook = new Facebook(APP_ID);
    private AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    private SharedPreferences mPrefs;

    // Buttons
    Button btnFbLogin;
    Button btnFbGetProfile;
    Button btnPostToWall;
    Button btnShowAccessTokens;
    Button Logout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
        btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
        btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
        btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
        Logout=(Button)findViewById(R.id.btn_show_Logout);
        mAsyncRunner = new AsyncFacebookRunner(facebook);

        /**
         * Login button Click event
         * */
        btnFbLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d("Image Button", "button Clicked");
                loginToFacebook();
            }
        });

        /**
         * Getting facebook Profile info
         * */
        btnFbGetProfile.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                getProfileInformation();
            }
        });

        /**
         * Posting to Facebook Wall
         * */
        btnPostToWall.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                postToWall();
            }
        });

        /**
         * Showing Access Tokens
         * */
        btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showAccessTokens();
            }
        });


        Logout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d("Logout Button CLicked", "button Clicked");
                logoutFromFacebook();
            }
        });

    }

    /**
     * Function to login into facebook
     * */
    public void loginToFacebook() {

        mPrefs = getPreferences(MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);

        if (access_token != null) {
            facebook.setAccessToken(access_token);

            btnFbLogin.setVisibility(View.INVISIBLE);

            // Making get profile button visible
            btnFbGetProfile.setVisibility(View.VISIBLE);

            // Making post to wall visible
            btnPostToWall.setVisibility(View.VISIBLE);

            // Making show access tokens button visible
            btnShowAccessTokens.setVisibility(View.VISIBLE);

            Logout.setVisibility(View.VISIBLE);

            Log.d("FB Sessions", "" + facebook.isSessionValid());
        }

        if (expires != 0) {
            facebook.setAccessExpires(expires);
        }

        if (!facebook.isSessionValid()) {
            facebook.authorize(this,
                    new String[] { "email", "publish_actions" },
                    new DialogListener() {

                        @Override
                        public void onCancel() {
                            // Function to handle cancel event
                        }

                        @Override
                        public void onComplete(Bundle values) {
                            // Function to handle complete event
                            // Edit Preferences and update facebook acess_token
                            SharedPreferences.Editor editor = mPrefs.edit();
                            editor.putString("access_token",
                                    facebook.getAccessToken());
                            editor.putLong("access_expires",
                                    facebook.getAccessExpires());
                            editor.commit();

                            // Making Login button invisible
                            btnFbLogin.setVisibility(View.INVISIBLE);

                            // Making logout Button visible
                            btnFbGetProfile.setVisibility(View.VISIBLE);

                            // Making post to wall visible
                            btnPostToWall.setVisibility(View.VISIBLE);

                            // Making show access tokens button visible
                            btnShowAccessTokens.setVisibility(View.VISIBLE);

                            Logout.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onError(DialogError error) {
                            // Function to handle error

                        }

                        @Override
                        public void onFacebookError(FacebookError fberror) {
                            // Function to handle Facebook errors

                        }

                    });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        facebook.authorizeCallback(requestCode, resultCode, data);
    }


    /**
     * Get Profile information by making request to Facebook Graph API
     * */
    public void getProfileInformation() {
        mAsyncRunner.request("me", new RequestListener() {
            @Override
            public void onComplete(String response, Object state) {
                Log.d("Profile", response);
                String json = response;
                try {
                    // Facebook Profile JSON data
                    JSONObject profile = new JSONObject(json);

                    // getting name of the user
                    final String name = profile.getString("name");

                    // getting email of the user
                    final String email = profile.getString("email");

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
                        }

                    });


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onIOException(IOException e, Object state) {
            }

            @Override
            public void onFileNotFoundException(FileNotFoundException e,
                    Object state) {
            }

            @Override
            public void onMalformedURLException(MalformedURLException e,
                    Object state) {
            }

            @Override
            public void onFacebookError(FacebookError e, Object state) {
            }
        });
    }

    /**
     * Function to post to facebook wall
     * */
    public void postToWall() {
        // post on user's wall.
        facebook.dialog(this, "feed", new DialogListener() {

            @Override
            public void onFacebookError(FacebookError e) {
            }

            @Override
            public void onError(DialogError e) {
            }

            @Override
            public void onComplete(Bundle values) {
            }

            @Override
            public void onCancel() {
            }
        });

    }

    /**
     * Function to show Access Tokens
     * */
    public void showAccessTokens() {
        String access_token = facebook.getAccessToken();

        Toast.makeText(getApplicationContext(),
                "Access Token: " + access_token, Toast.LENGTH_LONG).show();
    }

    /**
     * Function to Logout user from Facebook
     * */
    public void logoutFromFacebook() {
        mAsyncRunner.logout(this, new RequestListener() {
            @Override
            public void onComplete(String response, Object state) {
                Log.d("Logout from Facebook", response);
                if (Boolean.parseBoolean(response) == true) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // make Login button visible
                            btnFbLogin.setVisibility(View.VISIBLE);

                            // making all remaining buttons invisible
                            btnFbGetProfile.setVisibility(View.INVISIBLE);
                            btnPostToWall.setVisibility(View.INVISIBLE);
                            btnShowAccessTokens.setVisibility(View.INVISIBLE);
                            Logout.setVisibility(View.INVISIBLE);
                        }

                    });

                }
            }

            @Override
            public void onIOException(IOException e, Object state) {
            }

            @Override
            public void onFileNotFoundException(FileNotFoundException e,
                    Object state) {
            }

            @Override
            public void onMalformedURLException(MalformedURLException e,
                    Object state) {
            }

            @Override
            public void onFacebookError(FacebookError e, Object state) {
            }
        });
    }
2

There are 2 answers

0
Kumar On BEST ANSWER

I found the Solution for my Question

i replaced my Facebook SDK 3.0 to 3.2 .

also changed the code for facebook login.

now Logout and Login Working fine.

MainActivity.java

public class MainActivity extends FragmentActivity {
    String TAG="MainActivity";
    private static final String PERMISSION = "publish_actions";

    //private static final String PERMISSION = "email";

    private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";

    private Button postStatusUpdateButton;
    private LoginButton loginButton;
    private ProfilePictureView profilePictureView;
    private TextView greeting;
    private PendingAction pendingAction = PendingAction.NONE;
    private GraphUser user;
    private GraphPlace place;
    private List<GraphUser> tags;
    private boolean canPresentShareDialog;

    Button LogoutButton,Pro;

/*  private static final List<String> PERMISSION = Arrays.asList(
            "email","publish_actions");*/


    private enum PendingAction
    {
        NONE, POST_STATUS_UPDATE
    }

    private UiLifecycleHelper uiHelper;

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) 
        {
            onSessionStateChange(session, state, exception);
        }
    };

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall,
                Exception error, Bundle data) {
            Log.d(TAG, String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall,
                Bundle data) {
            Log.d(TAG, "Success!");
        }
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);
        // Can we present the share dialog for regular links?
        canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

        if (savedInstanceState != null) {
            String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }

        setContentView(R.layout.activity_main);



        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() 
        {
                    @Override
                    public void onUserInfoFetched(GraphUser user) 
                    {
                        MainActivity.this.user = user;
                        updateUI();
                        // It's possible that we were waiting for this.user to
                        // be populated in order to post a status update.
                        handlePendingAction();


                    }
                });

        profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
        greeting = (TextView) findViewById(R.id.greeting);

        postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
        postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
            }
        });

          LogoutButton=(Button)findViewById(R.id.LogoutButton);
          LogoutButton.setOnClickListener(new View.OnClickListener() 
          {

            @Override
            public void onClick(View v)
            {

                //callFacebookLogout(session);
                Logout();

            }
        });

    }

    //override lifecycle methods so that UiLifecycleHelper know about state of the activity
    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();
        updateUI();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    private void onSessionStateChange(Session session, SessionState state,Exception exception) 
    {
        if (state.isOpened()) {
            Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();

            getUserData(session,state);



        } else if (state.isClosed()) {
            Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
        }
        if (pendingAction != PendingAction.NONE
                && (exception instanceof FacebookOperationCanceledException 
                || exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(MainActivity.this)//if permission is not granted
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null).show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() 
    {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        postStatusUpdateButton.setEnabled(enableButtons
                || canPresentShareDialog);

        if (enableButtons && user != null) 
        {
            profilePictureView.setProfileId(user.getId());
            greeting.setText(getString(R.string.hello_user, user.getFirstName()));



        } else {
            profilePictureView.setProfileId(null);
            greeting.setText(null);
        }


    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
        case POST_STATUS_UPDATE:
            postStatusUpdate();
            break;
        }
    }

    private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

    private void showPublishResult(String message, GraphObject result,
            FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post,
                    message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null).show();
    }

    // create sample post to update on facebook
    private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
        return new FacebookDialog.ShareDialogBuilder(this)
                .setName("Hello Facebook")
                .setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
                .setLink("http://androidsrc.net/");
    }

    private void postStatusUpdate() {
        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        } else if (user != null && hasPublishPermission()) {
            final String message = getString(R.string.status_update,
                    user.getFirstName(), (new Date().toString()));
            Request request = Request.newStatusUpdateRequest(
                    Session.getActiveSession(), message, place, tags,
                    new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            showPublishResult(message,
                                    response.getGraphObject(),
                                    response.getError());
                        }
                    });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    //check if app has permission to publish on facebook
    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                // We need to get new permissions, then complete the action when
                // we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                        this, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }

    public void Logout()
    {
        if (Session.getActiveSession() != null) 
        {
            Session.getActiveSession().closeAndClearTokenInformation();
            Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
        }

        Session.setActiveSession(null);
    }




    private void getUserData(Session session, SessionState state)
    {
        if (state.isOpened())
        {
            Request.newMeRequest(session, new Request.GraphUserCallback()
            {
                @Override
                public void onCompleted(GraphUser user, Response response)
                {
                    if (response != null)
                    {
                        try
                        {
                            String name = user.getName();
                            // If you asked for email permission
                            String email = (String) user.getProperty("email");
                           // Log.e(LOG_TAG, "Name: " + name + " Email: " + email);

                            Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            //Log.d(LOG_TAG, "Exception e");
                        }

                    }
                }
            }).executeAsync();
        }
    }

My logout Method

public void Logout()
        {
            if (Session.getActiveSession() != null) 
            {
                Session.getActiveSession().closeAndClearTokenInformation();
                Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
            }

            Session.setActiveSession(null);
        }

Link i reffered

link

6
Hardik Trivedi On

If you are using latest facebook sdk 4.0 then

LoginManager.getInstance().logOut();

Will work.

dependencies {
    compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}