11

I am using restfb API to access my friend's photos in Java. And to access these photos, I generate access code manually using Graph API explorer and pass this as a parameter to the restfb API call.

But now I want to generate this access token through code (programmatically). I have seen fb android samples, particularly hackbook. I don't see any access code being generated which I can use for my own application. Do I need to create a new app and get some secret etc? Any suggestion will be appreciated.

I have seen these solutions (solution-1 & solution-2) on stackoverflow but I am still not getting where to start?

Update-1::

I am using following code to login and getting access token for logged in user. But the problem is that it only works for the account with which I had created an app on facebook to generate an app_id. It does not get a call back for other accounts. Any suggestion please.

And just in case if you don't know where to start, follow step-6 to create a new app from scratch.

public class MainActivity extends Activity implements OnClickListener {

    Button login;
    TextView accessToken;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        login = (Button) findViewById(R.id.login);
        accessToken = (TextView) findViewById(R.id.accessToken);

        login.setOnClickListener(this);
        // start Facebook Login


    }

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onResume()
    {
         Session session = Session.getActiveSession();
         if(session != null)
            if (session.isOpened()) {
                //Toast.makeText(this, session.getAccessToken(), Toast.LENGTH_LONG).show();
                accessToken = (TextView) findViewById(R.id.accessToken);
                accessToken.setText(session.getAccessToken());
                System.out.println("----------------------" + session.getAccessToken() + "---------------------");

            }
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        // start Facebook Login
        Session.openActiveSession(this, true, new Session.StatusCallback() {

            // callback when session changes state
            @Override
            public void call(Session session, SessionState state,
                    Exception exception) {
                if (session.isOpened()) {

                    // make request to the /me API
                    Request.executeMeRequestAsync(session,
                            new Request.GraphUserCallback() {

                                // callback after Graph API response with user
                                // object
                                @Override
                                public void onCompleted(GraphUser user,
                                        Response response) {
                                    if (user != null) {
                                        TextView welcome = (TextView) findViewById(R.id.welcome);
                                        welcome.setText("Hello "
                                                + user.getName() + "!");
                                    }
                                }
                            });
                }
            }
        });

    }

    }
Community
  • 1
  • 1
Junaid
  • 1,668
  • 7
  • 30
  • 51

4 Answers4

8

Using the Facebook SDK the better way to manage the authentication of the user is by means of the Session class. When you have a valid instance of the Session class you just have to call the getAccessToken() on it in order to obtain the String representing the access token.

Session session = Session.getActiveSession();
if (session != null && session.getState().isOpened()){
     Log.i("sessionToken", session.getAccessToken());
     Log.i("sessionTokenDueDate", session.getExpirationDate().toLocaleString());
}
5agado
  • 2,444
  • 2
  • 21
  • 30
  • thank you for the answer, I am not allowed create an object of Session. Please let me know why this happens! – TharakaNirmana May 11 '13 at 14:40
  • In fact you don't need to create a new Session instance, just use the `getActiveSession()` method, or `openActiveSession()` in case you get a null session from the previous one. Regard to this see also [my other answer](http://stackoverflow.com/questions/16140771/login-with-facebook-android-sdk-3-0-using-shared-preferences-session/16143102#16143102) – 5agado May 11 '13 at 17:03
  • Thank you for replying, my situation is a bit strange. I have a facebook object(Facebook facebook = new Facebook()). But with this object i cannot call facebook.getActiveSession() or facebook.openActiveSession(). Can u please tell me why? My intention is to somehow create an access token and send it with params(in bundle) to upload a photo. – TharakaNirmana May 11 '13 at 17:13
  • Those methods are from the Session class, not the Facebook one. In order to do do in the proper way what you want you to do I also suggest [this guide](http://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/) – 5agado May 11 '13 at 17:19
  • I assume that the `Session` class is not available in Facebook API 1.1 – Someone Somewhere Aug 08 '13 at 20:04
  • 1
    Is that a typo? If session == null, you're going to get a NullPointer when you reference session. – Marty Miller Sep 23 '13 at 23:10
8

I was having the same problem using the latest Facebook Android SDK (4.0.1).

I used AccessToken.getCurrentAccessToken() and it worked:

    GraphRequest request = GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject jsonObject, GraphResponse response) {
                    Log.d(LOG_TAG,"onCompleted jsonObject: "+jsonObject);
                    Log.d(LOG_TAG,"onCompleted response: "+response);
                    // Application code
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,link,cover,email");
    request.setParameters(parameters);
    request.executeAsync();
1

GET /oauth/access_token? client_id={app-id} &client_secret={app-secret} &grant_type=client_credentials

user3142006
  • 71
  • 1
  • 2
0

Answer to the original question has already been entered as update-1. But it was only working for admin users.

Actually during app creation, I had wrongly selected 'sandboxed' mode which restricts app's access only to developers added in app configuration page. So after disabling this mode, I was able to generate access token for other users too.

Junaid
  • 1,668
  • 7
  • 30
  • 51