将 Parse.Query 中的对象分配给全局变量

Assigning an object from Parse.Query to a global variable

我正在尝试通过解析访问查询中的变量,但它在查询完成时被销毁。 正如您在下面的代码中看到的,我将它输出到控制台并且它确实有效,但是如果我尝试将它分配给一个变量然后使用它 returns 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);
                    }
                }
            });

所以,基本上,您的问题似乎是您 运行 一个异步查询并试图在该查询返回之前访问该变量。

以下是如何设置代码以延迟使用变量,直到您可以合理地确定您有实际使用的值:

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