13

I'm trying to implement a simple activity in my android application where a user is asked to login via facebook so that the user's 'likes' are retrieved. So obviously first I'm testing a simple login via facebook. I'm using the exact code they have on 'Getting Started with the Facebook SDK for Android' - Step 6 (https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/) but for some reason it's not working. When I debugged the code I realised that the following condition:

if(session.isOpen()) 

is ALWAYS returning false even though I'd already be logged onto facebook. I've tried everything to fix it but nothing seems to be working.

Anybody had this issue or knows how to fix it?

EDIT: I'm trying this test on my phone directly not on an emulator. I don't know if that could be an issue.

Thanks in advance!

And I did try this solution session.isOpened() returns false even if successfully logged in to Facebook but using java 6 or 7 still gave the same hash key.

EDIT 2: I've also tried the same thing but with a slightly different approach. http://sonyarouje.com/2011/09/18/facebook-hash-key-for-android-apps/ I'm still having the same problem. The session.isOpen() method is always returning false.

EDIT 3: Here is the latest code I've tried. I don't think there are any errors in the logcat. Anyway I'll link it here just in case I'm missing something.

package com.example.danandroidapp;
import java.util.Arrays;

import com.facebook.FacebookException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    private String TAG = "MainActivity";
    private TextView lblEmail;

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

        lblEmail = (TextView) findViewById(R.id.lblEmail);

        LoginButton authButton = (LoginButton) findViewById(R.id.authButton);

        authButton.setOnErrorListener(new OnErrorListener() {
            @Override
            public void onError(FacebookException error) {
                Log.i(TAG, "Error " + error.getMessage());
            }
        });

        authButton.setReadPermissions(Arrays.asList("basic_info", "email"));
        authButton.setSessionStatusCallback(new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
            if(session.isOpened()) {
                Log.i(TAG, "Access Token " + session.getAccessToken());
                Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        if(user != null) {
                            Log.i(TAG, "User ID " + user.getId());
                            Log.i(TAG, "Email " + user.asMap().get("email"));
                            lblEmail.setText(user.asMap().get("email").toString());
                        }
                    }
                });
            }
        }
    });
}

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

}

And my logcat output: https://www.dropbox.com/s/7qg9zbhlpikfovf/log.txt

Daniel Grima
  • 2,765
  • 7
  • 34
  • 58

4 Answers4

9

I had the similar problem it was the hashkey was wrong in facebook, by following the below code you can get the hash key that has been sent to facebook. Just copy this hashkey and replace it. It will start working.

    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "your.root.package", 
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }
Ranjith
  • 510
  • 3
  • 10
  • Even though I had already solved it I thank you for the answer. That's exactly what I had to use. :) http://stackoverflow.com/questions/14486377/android-facebook-api-exception-remote-app-id-does-not-match-stored-id – Daniel Grima Jul 17 '13 at 09:55
  • @DanielGrima Can you tell how did you solve the problem? – aagam94 Dec 15 '13 at 17:15
  • @pOSEID0n just take a look at the answer in the link i posted above (http://stackoverflow.com/questions/14486377/android-facebook-api-exception-remote-app-id-does-not-match-stored-id) :) once you run that code it will output the hash key in the logcat, then make sure you copy and paste that hash key in the facebook app settings :) hope this helps – Daniel Grima Dec 19 '13 at 15:16
  • I set the hash key as you recommended, but the call back of openActiveSession() only gets called in 'Opening' state, so the session still not opened and I can't use it, any suggestions? ... Thank you – Ashraf Alshahawy Jan 16 '15 at 09:04
  • I found the answer to my question, I have to @Override onActivityResult() in my activity as in this answer: http://stackoverflow.com/questions/15194887/facebook-api-hangs-at-opening-during-openactivesession?answertab=votes#tab-top – Ashraf Alshahawy Jan 16 '15 at 09:14
  • How do you guys handle second time login? Once user logged in through facebook, what exactly happen on second login? Does session.isOpened added as check? – Mitesh Sharma Feb 13 '15 at 17:48
6

You're missing the onActivityResult override (the last bit of the code snippet in the Getting Started Guide).

The onActivityResult is how information gets from the FB app (or the webview) back into your app, and must be overridden to call back into the session.

Ming Li
  • 15,672
  • 3
  • 37
  • 35
  • I'll give that a go, I did try it before though. – Daniel Grima Apr 24 '13 at 17:45
  • I just tried the onActivityResult no luck once again. I've updated the logcat output as well just in case. – Daniel Grima Apr 24 '13 at 17:49
  • Can you try logging both the "state" and any "exception" in your callback's call() method? Also, can you ensure that your onActivityResult method is being called? – Ming Li Apr 24 '13 at 17:55
  • Ah I just realised that there's an error that I'm logging. First of all I debugged again and the onActivityResult is being called. However, I'm getting the following error here (authButton.setOnErrorListener) : "remote_app_id does not match stored id". I guess the app id is not correct? I don't understand as I'm 100% sure I'm using the app id provided by facebook. – Daniel Grima Apr 24 '13 at 18:05
  • 1
    This is due to your hashkey not being set correctly. There are many posts on SO already regarding how to figure out the correct hashkey (the one generated on the command line does not always match what's generated on device). – Ming Li Apr 24 '13 at 18:13
  • All right thanks a lot. Honestly I've always thought that it's a problem with my hash key. Unfortunately every time I tried it's always resulted in the same key via the command line. I've seen an example of generating the hash key for facebook via code. Maybe I should give that a try. – Daniel Grima Apr 24 '13 at 18:18
  • I finally managed to get it working. I generated the hashkey via code. (http://stackoverflow.com/questions/14486377/android-facebook-api-exception-remote-app-id-does-not-match-stored-id) – Daniel Grima Apr 25 '13 at 12:30
0
private Session.StatusCallback statusCallback = new SessionStatusCallback();

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

        try {
            new_session = session;
            if (state.equals(SessionState.OPENING)) {

            }

            if (state.equals(SessionState.OPENED)) {


            }

            if (state.equals(SessionState.CLOSED_LOGIN_FAILED)) {
                try {
                    PackageInfo info = context.getPackageManager()
                            .getPackageInfo("your package name",
                                    PackageManager.GET_SIGNATURES);
                    for (Signature signature : info.signatures) {
                        MessageDigest md = MessageDigest.getInstance("SHA");
                        md.update(signature.toByteArray());
                        Log.d("KeyHash:", Base64.encodeToString(
                                md.digest(), Base64.DEFAULT));
                    }
                    Session.openActiveSession((Activity) context, true,
                            statusCallback);
                } catch (NameNotFoundException e) {

                } catch (NoSuchAlgorithmException e) {

                }
            }

            if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) {



            }

    }
    catch(Exception e){}
  }
}

//if session is closed
Session.openActiveSession((Activity) context, true,
                    statusCallback);
0

You have to add the key hash on Facebook developer it works for me

JCLopez
  • 101
  • 1
  • 3