所以,在我的onCreate()方法中,我调用Parse查询并返回绑定到全局变量的单个ParseObject,如此......
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
String quizId = getActivity().getIntent().getStringExtra("quizId");
ParseQuery<ParseObject> getQuiz = ParseQuery.getQuery("Quiz");
getQuiz.getInBackground(quizId, new GetCallback<ParseObject>() {
@Override
public void done(ParseObject result, ParseException e) {
mQuiz = result;
mQuestionRelation = mQuiz.getRelation("questions");
Log.d("KMH", "mQuiz: " + mQuiz.getObjectId());
}
});
}
}
控制台将此作为获取对象的证据返回:
11-19 03:12:40.104 14876-14876/com.codejunkie.games.quizie D/KMH﹕ Parse returned quiz: HTgGeY3NJL
然后,我将全局ParseRelation变量设置为返回的ParseObject的关系。现在,在我的onResume()方法内部,我使用了这个Relation全局变量并获得了NullPointerException
。
@Override
public void onResume() {
super.onResume();
ParseQuery<ParseObject> getAnswers = mQuestionRelation.getQuery();
getAnswers.addDescendingOrder("createdAt");
getAnswers.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> answers, ParseException e) {
mAnswers = answers;
String[] answerText = new String[mAnswers.size()];
int i = 0;
for(ParseObject answer : mAnswers) {
answerText[i] = answer.getString("answer");
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout._item_question, R.id.questionText, answerText);
setListAdapter(adapter);
}
});
}
这是NullPointer
:
ParseQuery<ParseObject> getAnswers = mQuestionRelation.getQuery();
解答:
由于.getInBackground调用Parse,我没有在主线程中设置我的全局变量。以下是我修复它的方法:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
String quizId = getActivity().getIntent().getStringExtra("quizId");
ParseQuery<ParseObject> getQuiz = ParseQuery.getQuery("Quiz");
try {
mQuiz = getQuiz.get(quizId);
mQuestionRelation = mQuiz.getRelation("questions");
} catch (ParseException e) {
e.printStackTrace();
}
}
}
并处理mQuestionRelation为null
的情况:
if (mQuestionRelation != null) {
ParseQuery<ParseObject> getQuestions = mQuestionRelation.getQuery();
getQuestions.addAscendingOrder("createdAt");
getQuestions.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> questions, ParseException e) {
if (e == null) {
mQuestions = questions;
String[] answerText = new String[mQuestions.size()];
int i = 0;
for (ParseObject question : mQuestions) {
answerText[i] = question.getString("question");
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout._item_question, R.id.questionText, answerText);
mQuestionsList.setAdapter(adapter);
}
}
});
}
答案 0 :(得分:2)
您可以在另一个线程中获取您的Relation(因为它在后台执行)。这意味着该集合实际上并未在onCreate()中完成,但有时甚至更晚,所以&#39; done&#39;可以在onResume()之后调用方法,具体取决于查询的速度。如果发生这种情况,那么你确实会得到一个空指针异常。