在IntentService中从Firestore获取数据的问题

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

您知道为什么IntentService代码中的dataFromDatabase总是返回null吗?

collection.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
  @Override
  public void onSuccess(DocumentSnapshot documentSnapshot) {
      dataFromDatabase = documentSnapshot.get("name").toString();
  }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        dataFromDatabase = "Error";
    }
});

用户已登录,userID返回其ID的正确值。

Firestore数据库如下所示:Firestore database

这是我的IntentService的完整代码:

public class AppWidgetService extends IntentService {

    String dataFromDatabase;
    String userID;

    public static final String ACTION_FOO = "pl.skawit.challenge.action.FOO";

    public AppWidgetService() {
        super("AppWidgetService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                handleActionFoo();
            }
        }
    }

    private void handleActionFoo() {
        FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
        userID = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid();
        DocumentReference collection = firebaseFirestore.document("users_data/" + userID);

        collection.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
              @Override
              public void onSuccess(DocumentSnapshot documentSnapshot) {
                  dataFromDatabase = documentSnapshot.get("name").toString();
              }
          })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                dataFromDatabase = "Error";
            }
        });


}
android google-cloud-firestore intentservice
1个回答
0
投票

[我发现了类似的帖子,其中说您如果documentSnapshot为null,并且您确定该文档存在,那么问题可能是由权限[1]引起的。

[1] DocumentSnapshot is always null for a valid document reference

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