Working with asynchronous callbacks in Java

One of my OpenFeint methods for recovering leader data requires an asynchronous callback for a method that should change one of my local variables (using a wonderful hack). My problem is that after CB is called a continuation, and since the score value has not changed yet, it returns nullPointer. Any way to make everything synchronize or return a callback value from the main function?

private long getScoreLeaderBoard(String idLeaderBoard) {
    for (Leaderboard l : OpenFeintX.leaderboards) {
        if (l.name == null)
            break;
        if (l.resourceID().equalsIgnoreCase(idLeaderBoard)) {
            final Score s[] = new Score[1];
            l.getUserScore(OpenFeint.getCurrentUser(),
                    new Leaderboard.GetUserScoreCB() {

                        @Override
                        public void onSuccess(Score score) {
                            s[0] = score;
                        }
                    });
            if (s[0] != null) // If user has no score onSuccess get a null
                return s[0].score;
            else
                return 0;
        }
    }

    return 0;
}

Callback definition: http://m.the9.com/ioshelp/Android_en/doc/com/openfeint/api/resource/Leaderboard.GetUserScoreCB.html

+3
source share
3 answers

onPostExecute AsyncTask ,

0

, CountDownLatch :

private long getScoreLeaderBoard(String idLeaderBoard) {
    final CountDownLatch cdl = new CountDownLatch(1);
    ...
                    @Override
                    public void onSuccess(Score score) {
                        s[0] = score;
                        cdl.countDown();
                    }
    ...
        cdl.await();
        return s[0].score;
    ...
}
0

instead

private long getScoreLeaderBoard(String idLeaderBoard) { /* takes long */ }

do it

private void requestScoreLeaderBoardUpdate(String idLeaderBoard) { /* takes long */ }

and put the code that handled the getScoreLeaderBoard return value into (or called its method) onSuccess.

This way you do not need to wait and block the thread.

You can also allow their implementation to realize Leaderboard.GetUserScoreCBand then use a different method onCreate, onClick....

class MyActivity extends Activity implements Leaderboard.GetUserScoreCB {

    private void requestScoreLeaderBoardUpdate(String idLeaderBoard) {
        // ..
        l.getUserScore(OpenFeint.getCurrentUser(), this /* your activity */);
    }

    @Override
    public void onSuccess(Score score) {
        s[0] = score;
        // do anything you want with the new score here
    }
}
0
source

All Articles