我试图从解析中访问查询中的变量,但在查询完成时会被销毁。 正如您在下面的代码中看到的那样,我将其输出到控制台并且它确实有效,但如果我尝试将其分配给变量然后使用它,则返回null。任何帮助将不胜感激。
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("Codigo", id);
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The getFirst request failed.");
} else {
Log.d("id", "Retrieved the object.");
String status = object.getString("Hospital");
m2Status = object.getString("Hospital");
System.out.println("Hospital: " + status);
System.out.println(status + m2Status);
}
}
});
答案 0 :(得分:0)
因此,基本上,您的问题似乎是您正在运行异步查询并尝试在该查询返回之前访问该变量。
以下是如何设置代码以推迟使用变量,直到您可以合理地确定您有实际使用的值为止:
private void runQuery() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("Codigo", id);
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The getFirst request failed.");
// You don't have a good value to use, so figure
// out a way to handle that scenario
} else {
Log.d("id", "Retrieved the object.");
String status = object.getString("Hospital");
m2Status = object.getString("Hospital");
System.out.println("Hospital: " + status);
System.out.println(status + m2Status);
// You have a good value to use, so
// now you can actually use it
afterQueryProcessing();
}
}
});
}
private void afterQueryProcessing() {
// You can access m2Status here reliably,
// assuming you only call this method
// as shown above, but you should still
// use defensive programming
if (m2Status != null) {
// Now you know you have a value to use...
}
}