smb6
smb6

Reputation: 121

Unable to use the result of a ParseQuery

I'm using Parse and I'm doing a query to fetch a table . As you can see in the code below, the list LOCALparseQuestionList is populated correctly during the for loop inside the findInBackground. Once it's done, the LOCALparseQuestionList is empty (the log prints 0 size and I see the same when using the debugger). How should I fetch correctly the data and populate my 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;
}

Upvotes: 0

Views: 62

Answers (1)

danh
danh

Reputation: 62686

Its a the number one misunderstanding about asynchronous functions: the code underneath the find function does not run after the find function. It runs before it.

The last log statement in the function logs, and the return statement returns an empty list, because that list is populated later, after the find is done and the results are returned. Anything you do that depend on LOCALparseQuestionList being populated must be done within the find's callback.

Upvotes: 2

Related Questions