0

Using Facebook SDK in an Android application is simply making my days worse. I seem to loose the session from time to time, the hash does not seem to be right sometimes. The current error says that the hashkey * is not the same as the one registered. Which it's not correct, that hashkey is registered in their platform for the app(the app is public as well).

This is the class i am using to connect to facebook. After i choose to login, i get the dialog stating the permissions, (would like to see the list of friends..) and after i choose OK or Cancel..nothing happends. Session is closed.

import java.util.Properties;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.FacebookOperationCanceledException;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;

public class Test extends Activity {

    private GraphUser user = null;
    private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";
    private Session.StatusCallback statusCallback = new SessionStatusCallback();
    private final String TAG = "Login with facebook";
    private Session session;

    // gcm
    public static final String EXTRA_MESSAGE = "message";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    public static final String PROPERTY_REG_ID = "registration_id";

    private Properties properties;

    // Facebook
    private UiLifecycleHelper uiHelper;

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

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);

        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));
            }
            Log.d(TAG, "Session state: " + session.getState());
        }

        if (session.isOpened()) {
            Log.d(TAG, "Access token: " + session.isOpened());
            System.out.println(session.getAccessToken());
        } else {
            onClickLogin();
        }
    }

    @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 onClickLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this)
                    .setCallback(statusCallback));
        } else {
            Session.openActiveSession(this, true, statusCallback);
        }
    }

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

            onSessionStateChange(session, state, exception);

        }
    }

    private void onSessionStateChange(final Session session,
            SessionState state, Exception exception) {
        if (session != null && session.isOpened()) {
            if (!state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
                makeMeRequest(session);
            }
        }
        if (exception instanceof FacebookOperationCanceledException) {
            // Cancelled by user, show alert
            new AlertDialog.Builder(Test.this)
                    .setTitle(getString(R.string.hello))
                    .setMessage(getString(R.string.back_in_facebook_login))
                    .setPositiveButton(R.string.got_it, new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(
                                    Test.this,
                                    LaunchingActivity.class));
                            finish();
                        }
                    }).show();
        }
    }

    private void makeMeRequest(final Session session) {
        // Make an API call to get user data and define a
        // new callback to handle the response.
        Request request = Request.newMeRequest(session,
                new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        // If the response is successful
                        if (session == Session.getActiveSession()) {
                            if (user != null) {

                                if (session.isOpened()) {
                                    // yey. you have a valid session
                                }
                            }
                        }
                        if (response.getError() != null) {
                            // Handle errors, will do so later.
                        }
                    }
                });
        request.executeAsync();
    }

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

    public void show(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(Test.this, message,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    public interface SkipLoginCallback {
        void onSkipLoginPressed();
    }

    public void setSkipLoginCallback(SkipLoginCallback skipLoginCallback2) {
        // skipLoginCallback = skipLoginCallback2;
    }

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

In manifest.xml:

<!-- Facebook -->
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />


        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/fb_app_id" />
        <!-- end -->

In the layout:

<com.facebook.widget.LoginButton
            android:id="@+id/fbLoginBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />

Error log:

W/fb4a(:<default>):BlueServiceQueue(11190): Exception during service
W/fb4a(:<default>):BlueServiceQueue(11190): com.facebook.http.protocol.ApiException: Key hash ****************** does not match any
 stored key hashes.
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponseChecker.b(ApiResponseChecker.java:83)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponseChecker.a(ApiResponseChecker.java:162)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponse.g(ApiResponse.java:186)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.platform.server.protocol.AuthorizeAppMethod.a(AuthorizeAppMethod.java:274)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.platform.server.protocol.AuthorizeAppMethod.a(AuthorizeAppMethod.java:30)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponseHandler.a(ApiResponseHandler.java:56)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponseHandler.handleResponse(ApiResponseHandler.java:29)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.common.FbHttpRequestProcessor.a(FbHttpRequestProcessor.java:318)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.common.FbHttpRequestProcessor.a(FbHttpRequestProcessor.java:147)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.common.FbHttpRequestProcessor.b(FbHttpRequestProcessor.java:104)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.common.FbHttpRequestProcessor.a(FbHttpRequestProcessor.java:234)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.SingleMethodRunnerImpl.a(SingleMethodRunnerImpl.java:380)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.SingleMethodRunnerImpl.a(SingleMethodRunnerImpl.java:161)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.AbstractSingleMethodRunner.a(AbstractSingleMethodRunner.java:1
8)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.platform.server.common.SimplePlatformOperation.a(SimplePlatformOperation.jav
a:40)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.platform.server.handler.PlatformOperationHandler.a(PlatformOperationHandler.
java:61)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.fbservice.service.BlueServiceQueue.e(BlueServiceQueue.java:300)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.fbservice.service.BlueServiceQueue.d(BlueServiceQueue.java:53)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.fbservice.service.BlueServiceQueue$3.run(BlueServiceQueue.java:230)
W/fb4a(:<default>):BlueServiceQueue(11190):     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/fb4a(:<default>):BlueServiceQueue(11190):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.common.executors.ListenableScheduledFutureImpl.run(ListenableScheduledFuture
Impl.java:59)
W/fb4a(:<default>):BlueServiceQueue(11190):     at android.os.Handler.handleCallback(Handler.java:733)
W/fb4a(:<default>):BlueServiceQueue(11190):     at android.os.Handler.dispatchMessage(Handler.java:95)
W/fb4a(:<default>):BlueServiceQueue(11190):     at android.os.Looper.loop(Looper.java:136)
W/fb4a(:<default>):BlueServiceQueue(11190):     at android.os.HandlerThread.run(HandlerThread.java:61)
W/fb4a(:<default>):GDPDialog(11190): Failed to send
W/fb4a(:<default>):GDPDialog(11190): com.facebook.fbservice.service.ServiceException: API_ERROR: API_ERROR
W/fb4a(:<default>):GDPDialog(11190):    at com.facebook.fbservice.ops.BlueServiceOperation.c(BlueServiceOperation.java:640)
W/fb4a(:<default>):GDPDialog(11190):    at com.facebook.fbservice.ops.BlueServiceOperation.c(BlueServiceOperation.java:48)
W/fb4a(:<default>):GDPDialog(11190):    at com.facebook.fbservice.ops.BlueServiceOperation$2.run(BlueServiceOperation.java:605)
W/fb4a(:<default>):GDPDialog(11190):    at android.os.Handler.handleCallback(Handler.java:733)
W/fb4a(:<default>):GDPDialog(11190):    at android.os.Handler.dispatchMessage(Handler.java:95)
W/fb4a(:<default>):GDPDialog(11190):    at android.os.Looper.loop(Looper.java:136)
W/fb4a(:<default>):GDPDialog(11190):    at android.app.ActivityThread.main(ActivityThread.java:5017)
W/fb4a(:<default>):GDPDialog(11190):    at java.lang.reflect.Method.invokeNative(Native Method)
W/fb4a(:<default>):GDPDialog(11190):    at java.lang.reflect.Method.invoke(Method.java:515)
W/fb4a(:<default>):GDPDialog(11190):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
W/fb4a(:<default>):GDPDialog(11190):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
W/fb4a(:<default>):GDPDialog(11190):    at dalvik.system.NativeStart.main(Native Method)

Hope somebody notices a mistake of mine, cause I don't understand any of this now. Thanks

Gabriela Radu
  • 757
  • 2
  • 12
  • 33

1 Answers1

1

Try calling Session.getActiveSession without specifying it to your Session object. That should trigger the callback. Then in your onSessionStateChange(...) method, do your conditional to check if the session is opened or not.

Doing all that session checking in onCreate(...) could work better if it's moved into the onSessionStateChange(...), provided you can get the callback to trigger.

EDIT: Try to also manually set the callback to your LoginButton. I think there's a .setCallback(...) method for LoginButton.I had some trouble getting the callback to trigger from the button not too long ago as well.

Wenger
  • 989
  • 2
  • 12
  • 35
  • hello, i replaced using the Session object and instead used Sesssion.getActiveSession(). When debugging(each step...) it throws this error :com.facebook.FacebookAuthorizationException: UnknownError: ApiException:Key hash H-****-****-***.. does not match any stored key hashes. again. And i have added this hash to the console for the app. – Gabriela Radu Jan 24 '14 at 01:15
  • This helped and worked: http://stackoverflow.com/questions/19485004/android-app-key-hash-doesnt-match-any-stored-key-hashes – Gabriela Radu Jan 24 '14 at 01:23