Reputation: 57
I am quite new to Java/android programming and I'm stuck at the Parse.com callback.
In have a method (method1) that requests the objectId of an object owned by the current user. It does this by calling upon another method (method2) that contains a query which pulls an object from the data browser with a callback.
I managed to write all code but I'm stuck at the callback for method 2. I want the object data to be returned to method 1 but this seems to be inpossible because of the Callback type (void).
I also do now know how to let the rest of the method wait for the callback to return before executing.. I would appreciate it if anyone could help me out.
This is my code:
public void method1(){
String objectId = null;
objectId = QueryStatisticObjectId("Age");
Log.i(TAG, "objectId returned to method = " + objectId);
}
public String QueryStatisticObjectId(final String statistic){
ParseQuery<ParseObject> query = ParseQuery.getQuery("Statistics");
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.whereEqualTo("statistic", statistic);
query.getFirstInBackground(new GetCallback<ParseObject>() {
@Override
public void done(ParseObject object, ParseException e) {
if (e == null){
//We have data!
String objectId = object.getObjectId();
return;
}
else
{
//Something went wrong!?!
e.printStackTrace();
}
}
});
Upvotes: 1
Views: 2270
Reputation:
I am having the same issue, the callbacks are really annoying, seems like they fire randomly, and the return type of void makes Overriding everything neccessary. I solved your problem by using regular .find() without the callback. I then did all the grunt work using custom code.
Upvotes: 0
Reputation: 11598
So, what you're trying to do isn't available using Parse in iOS or Android. I think it will probably work the way you want on .NET (using the Await keyword).
Instead, ask yourself:
If so, try something like this:
public void method1() {
QueryStatisticObjectId("Age", new GetCallback<ParseObject>() {
@Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
String objectId = object.getObjectId();
Log.i(TAG, "objectId returned to method = " + objectId);
} else {
Log.i(TAG, "objectId not found");
}
}
});
}
public void QueryStatisticObjectId(final String statistic, GetCallback<ParseObject> callback) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Statistics");
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.whereEqualTo("statistic", statistic);
query.getFirstInBackground(callback);
}
In this way, you can write the code to handle the returned result in the context (method1()
) that makes sense, while also re-using the query method as much as you like. Additionally, as opposed to @JimW's answer, this doesn't utilize synchronous web calls, which will also afford you the opportunity to keep your app's UI responsive.
Upvotes: 2