androidgoogle-cloud-firestoreintentservice

Problem with getting data from Firestore in IntentService


Do you know why dataFromDatabase in IntentService code always returns 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";
    }
});

The user is logged in and userID returns correct value of his ID.

Firestore database looks like this: Firestore database

This is full code of my 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";
            }
        });


}

Solution

  • I found a similar post where it says your if documentSnapshot is null and you're sure the document exists, then the problem can be caused by permissions [1].

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