解析查询:从类中的done()方法返回一个值?

时间:2016-01-09 23:53:28

标签: java android parse-platform

我遇到以下问题:

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

我想返回值totalPoints以在我的MainActivity中使用它。我尝试将它放在方法中并改为使用void类,但后来我找不到如何调用它。知道如何解决这个问题吗? 谢谢

1 个答案:

答案 0 :(得分:0)

问题是,当您不想在后台查找时,您正在使用findInBackground方法。请改用find方法:

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

注意:通常我会通过ParseException或转换为Runtime,因为调用者可能需要对它执行某些操作。