androidfacebook-graph-apirequestfacebook-sdk-3.14.x

FB Android-SDK: How to wait until callback of request is completed


I am trying to wait until onCompleted() of my callback function of a Request is finished. However the method get() of the RequestAsyncTask always returns before this is the case. Therefore it comes to problems in the further statements of my program. The println output is always displayed after the database query and is not equal null. Here is my code:

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) {
            // show authendicated ui
            Log.i(TAG, "Logged in...");
            try {
                Request.newMeRequest(session, new Request.GraphUserCallback() {

                    // callback after Graph API response with user object
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        if (user != null) {
                            MyApplication.userId = user.getId();
                            System.out.println("User id: " + MyApplication.userId);
                        }

                    }
                }).executeAsync().get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            boolean isNewUser = !MyApplication.dbConnection.isUidRegistered(MyApplication.userId);

This causes my database to look up for null as uid. How can I solve this problem?


Solution

  • You should put this part of your code:

    boolean isNewUser = !MyApplication.dbConnection.isUidRegistered(MyApplication.userId);
    

    inside your Request callback:

     @Override
    public void onCompleted(GraphUser user, Response response) {
        if (user != null) {
            MyApplication.userId = user.getId();
            System.out.println("User id: " + MyApplication.userId);
    
            boolean isNewUser = !MyApplication.dbConnection.isUidRegistered(MyApplication.userId);
            // here you should continue your work
        }    
    }