FB Android-SDK:如何等待请求回调完成

时间:2014-06-06 20:23:14

标签: android facebook-graph-api request facebook-sdk-3.14.x

我正在尝试等待onCompleted()的回调函数Request完成。但是,在此情况之前,get()的方法RequestAsyncTask始终会返回。因此,我的程序的进一步陈述中出现了问题。 println输出始终在数据库查询后显示,并且不等于null。 这是我的代码:

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

这会导致我的数据库以null作为uid查找。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你应该把这部分代码放在一边:

boolean isNewUser = !MyApplication.dbConnection.isUidRegistered(MyApplication.userId);
在请求回调中

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