Login to facebook a button to open a new activity

defiant picture defiant · Dec 14, 2012 · Viewed 7.5k times · Source

I am trying to login to facebook once the user clicks on a button and then once successfully logged in, the new activity is created.

This is the code of the main activity so far!

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;

public class MainActivity extends Activity {

    @SuppressWarnings("unused")
    private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";
    private Session.StatusCallback statusCallback = new SessionStatusCallback();
    private ImageButton fbImgButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fbImgButton = (ImageButton)findViewById(R.id.imageView2);

        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);
    }

    private void updateView() {
        Session session = Session.getActiveSession();
        if(session.isOpened()) {
            Toast.makeText(getApplicationContext(), "Logged in....", Toast.LENGTH_LONG).show();
            fbImgButton.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { loginfb(); }
            });
        } else {
            fbImgButton.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogin(); }
            });
        }
    }

    public void loginfb() {
        //start the new activity here
        //Toast.makeText(getApplicationContext(), "Works first", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(MainActivity.this, SelectionFragment.class);
        MainActivity.this.startActivity(intent);

    }

    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);
        }
        Intent intent = new Intent(MainActivity.this, SelectionFragment.class);
        MainActivity.this.startActivity(intent);
    }

    public void shareOnTwitter(View v) {
        EditText widget40 = (EditText)findViewById(R.id.widget40);
        Uri uri = Uri.parse("https://twitter.com/intent/tweet?text=" + " @coolfacts_fb " + widget40.getText());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    public void nofb(View v) {
        Intent intent = new Intent(v.getContext(), shareTw.class);
        startActivityForResult(intent, 0);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;

    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            updateView();
        }
    }
}

The problem is, no matter what is the current state of the user, if goes to the new activity as soon as I click the button for facebook login!

Can somebody please help me?

Answer

Pratik Sharma picture Pratik Sharma · Dec 15, 2012

Try with this :

public class MainActivity extends Activity {

    @SuppressWarnings("unused")
    private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";
    private Session.StatusCallback statusCallback = new SessionStatusCallback();
    private ImageButton fbImgButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fbImgButton = (ImageButton)findViewById(R.id.imageView2);

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        // Add Session Callback Here
        Session.getActiveSession().addCallback(statusCallback);

        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));
            }

            // Get Avtive Session again in case of session is null  
            Session session = Session.getActiveSession();
        }

    // Dont call updateView() here as we have called this from session callback already.
    // 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);
    }

    // Minor changes made with updateView() Method flow
    private void updateView() {
        Session session = Session.getActiveSession();    
        fbImgButton.setOnClickListener(new OnClickListener() {
          public void onClick(View view) {      
           if(session.isOpened()){
              Toast.makeText(getApplicationContext(), "loginfb...", Toast.LENGTH_LONG).show();   
              loginfb(); 
           }
           else{
              Toast.makeText(getApplicationContext(), "onClickLogin...", Toast.LENGTH_LONG).show();
              onClickLogin();
           }
          }
       });
    }

    public void loginfb() {
        //start the new activity here
        //Toast.makeText(getApplicationContext(), "Works first", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(MainActivity.this, SelectionFragment.class);
        MainActivity.this.startActivity(intent);

    }

    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);
        }
        Intent intent = new Intent(MainActivity.this, SelectionFragment.class);
        MainActivity.this.startActivity(intent);
    }

    public void shareOnTwitter(View v) {
        EditText widget40 = (EditText)findViewById(R.id.widget40);
        Uri uri = Uri.parse("https://twitter.com/intent/tweet?text=" + " @coolfacts_fb " + widget40.getText());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    public void nofb(View v) {
        Intent intent = new Intent(v.getContext(), shareTw.class);
        startActivityForResult(intent, 0);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;

    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            updateView();
        }
    }
}

Check this for onCreate() and onStart() difference. It clearly shows onCreate() called first before onStart() so we also need to add session callback from onCreate() method too.

Difference between onCreate() and onStart()

Note : You can keep your updateView() method as it is also, there is nothing wrong logically.

Hope this helps you.

Thanks.