Firestore getCount方法返回任务。如何转换为int或String?

问题描述 投票:0回答:2

我正在使用Firestore分片来跟踪集合中的文档数量。如何将它返回的任务转换为String?

我的方法(与Firebase文档相同):

public Task<Integer> getCount(final DocumentReference ref) {
    // Sum the count of each shard in the subcollection
    return ref.collection("shards").get()
            .continueWith(new Continuation<QuerySnapshot, Integer>() {
                @Override
                public Integer then(@NonNull Task<QuerySnapshot> task) throws Exception {
                    int count = 0;
                    for (DocumentSnapshot snap : task.getResult()) {
                        Shard shard = snap.toObject(Shard.class);
                        count += shard.count;
                    }
                    Log.d(TAG, Integer.toString(count));
                    return count;
                }
            });
}

正确记录计数如下:D/saveMessageSent: 1

但是,当我在其他地方调用getCount方法时:

Log.d(TAG, String.valueOf(getCount(counterDocRef)));

那么日志输出是:

D/saveMessageSent: com.google.android.gms.tasks.zzu@8673e29

我似乎无法将其转换为字符串,因为它说它是一个

com.google.android.gms.tasks.Task<java.lang.Integer>

我怎么解决这个问题,所以当我调用getCount时它会给我一个我可以使用的int?

android firebase task google-cloud-firestore
2个回答
2
投票

您不会将Task对象转换为其他类型的对象。您使用Task API在回调中接收异步任务的结果。例如,如果您有一个Task,它将在成功回调中产生一个Integer:

task.addOnSuccessListener(new OnSuccessListener<Integer>() {
    @Override
    public void onSuccess(Integer i) {
        // i is the Integer result of the task.
    }
});

0
投票

你可能认为,你的getCount()方法的返回类型是Task<Integer>而不是Integer。确实,当初始化Continuation类(实际上是一个匿名类)时,重写方法的返回类型为Integer,但这不是封闭的getCount()方法的返回类型。所以这个方法永远不会返回一个Integer对象。

当您尝试使用以下语句时:

Log.d(TAG, String.valueOf(getCount(counterDocRef)));

它不会打印整数,因为你传递给valueOf()方法一个Task<Integer>对象而不是Integer,这就是为什么你得到那个奇怪的日志语句。实际打印的是该对象从内存中的实际地址。

要解决这个问题,你应该只在内部count方法中使用then的值。如果您想要计算集合中的所有文档,请参阅我的post的答案。

你也可以使用addOnSuccessListener,正如@Doug Stevenson在他的回答中提到的那样,这是一种更简单和更优雅的方式。

© www.soinside.com 2019 - 2024. All rights reserved.