简体   繁体   中英

Parse Query: return a value from the done() method in the class?

I have a problem with the following:

public int getPoints() {
    ParseQuery<RoyalPoints> pointsQuery = RoyalPoints.getQuery();
    pointsQuery.whereEqualTo("user", ParseUser.getCurrentUser());
    pointsQuery.findInBackground(new FindCallback<RoyalPoints>() {
        @Override
        public void done(List<RoyalPoints> list, ParseException e) {
            if (e == null) {
                i = 0;
                for (RoyalPoints obj : list) {
                    totalPoints = totalPoints + obj.getInt("points");
                    i = i + 1;
                }
            } else {
                Log.d("Points retrieval", "Error: " + e.getMessage());
            }
        }
    });
    return totalPoints;
}

I want to return the value totalPoints to use it in my MainActivity. I tried putting it in the method and having a void class instead but I can't find how to call it afterwards. Any idea how I can solve this? Thank you

The problem is that you are using the findInBackground method when you don't want to find in the background. Use the find method instead:

  public int getPoints() {
      try {
         ParseQuery<RoyalPoints> pointsQuery = RoyalPoints.getQuery();
         pointsQuery.whereEqualTo("user", ParseUser.getCurrentUser());
         List<RoyalPoints> list = pointsQuery.find();
         for (RoyalPoints obj : list) {
            totalPoints = totalPoints + obj.getInt("points");
         }

         return totalPoints;
     } catch (ParseException e) {
         Log.d("Points retrieval", "Error: " + e.getMessage());
     }
  }

Note: Normally I would through the ParseException or convert to Runtime as the caller may need to do something with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM