I'm using facebook SDK for Android. I have a request which has a callback from where I get the response. I have to execute the request a variable number of times depending on the response I get from the request. I'm trying to use a global variable outside the callback function and update it using the response but it's not working. Here is how I'm taclkling it.
The global variable:
int dataLength = -1;
To continually execute the request:
while (dataLength == -1){
getComments("20");
}
The issue is that it is as if the dataLength is never being updated though it should be updated on the very first call
The request and callback function:
public void getComments(String offset){
GraphRequest request = GraphRequest.newGraphPathRequest(AccessToken.getCurrentAccessToken(), "/me/inbox",
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse graphResponse) {
dataLength = graphResponse.getJSONObject().getJSONArray("data").length;
}
});
Bundle parameters = new Bundle();
parameters.putString("limit", "20");
parameters.putString("offset", offset);
request.setParameters(parameters);
request.executeAsync();
}
One problem is that your while-loop and your asynchronous callback are running in separate threads, so without some sort of synchronization, there is no guarantee that values of
dataLength
written in one thread will be read in the other. (See "Memory Consistency Errors" in the Java Tutorials.)The simplest fix for that problem is to tack on the
volatile
keyword:This ensures that each read of
dataLength
will retrieve the latest-written value.