无法使用ParseQuery的结果

时间:2015-05-27 22:07:22

标签: android parse-platform

我正在使用Parse,我正在进行查询以获取表格。 正如您在下面的代码中看到的,列表LOCALparseQuestionList在findInBackground中的for循环期间正确填充。一旦完成,LOCALparseQuestionList为空(日志打印0大小,我在使用调试器时看到相同)。 我该如何正确获取数据并填充我的LOCALparseQuestionList?

 public List<QuestionStruct> getParseAllQuestions() {
    final List<QuestionStruct> LOCALparseQuestionList = new ArrayList<QuestionStruct>();
    // Select All Query
    ParseQuery<ParseObject> questionQuery = ParseQuery.getQuery("triviaQuestions");
    questionQuery.findInBackground(new FindCallback<ParseObject>() {
        public void done(List<ParseObject> allQuestions, ParseException e) {
            if (e == null) {
                parseQuestionList = allQuestions;
                Log.d(TAG, "Retrieved " + allQuestions.size() + " All questions");
                for (ParseObject qu : allQuestions) {
                    QuestionStruct currentQuestion = new QuestionStruct();
                    currentQuestion.setID(qu.getInt("id"));
                    currentQuestion.setQuestion(qu.getString("question"));
                    currentQuestion.setCorrectAnswer(qu.getString("correct"));
                    currentQuestion.setPossibleAnswer(qu.getString("wrong_1"));
                    currentQuestion.setPossibleAnswer(qu.getString("wrong_2"));
                    currentQuestion.setPossibleAnswer(qu.getString("wrong_3"));
                    currentQuestion.setPossibleAnswer(qu.getString("correct"));
                    LOCALparseQuestionList.add(currentQuestion);
                    Log.d(TAG, "Retrieved  " + LOCALparseQuestionList.size() + " LOCALparseQuestionList ");
                }
            } else {
                Log.d(TAG, "Error: " + e.getMessage());
            }
        }
    });
    Log.d(TAG, "questionList size: " + LOCALparseQuestionList.size());

    return LOCALparseQuestionList;
}

1 个答案:

答案 0 :(得分:2)

它是关于异步函数的头号误解:find函数下面的代码不会在find函数之后运行。它在它之前运行。

函数日志中的最后一个日志语句,并且return语句返回一个空列表,因为稍后在查找完成并返回结果后填充该列表。任何依赖于LOCALparseQuestionList填充的操作都必须在find的回调中完成。