Wednesday 30 June 2021

Android - Transaction - Task is not yet complete

I found a few examples of "task not yet complete," but have not found any examples for transactions. I am using a transaction because in my application I need the operation to be able to fail if there is no internet connection. I can detect this with a transaction.

I have a Collection with Documents. I am trying to obtain the names of the documents. Sometimes the code works fine, but majority of the time I get the "task not yet complete" error. The frustrating thing is that I have a callback for "onComplete" so it's weird that the transaction isn't complete when the callback is... called.

I get the "task not yet complete exception in the onCompleteListener(). What's frustrating is that I even check to ensure if (task.isSuccessful() && task.isComplete()). Do I need to use a continuation? If so, please provide an example - I just don't quite understand it yet.

// Note: states is an ArrayList<String>
//       snapshot is a QuerySnapshot

public void getStatesList(){

    states.clear(); 
    states.add("Select A State");

    db.runTransaction(new Transaction.Function<Void>() {
        @Nullable
        @Override
        public Void apply(@NonNull Transaction transaction) {
            // Collect Snapshot data
            snapshot = db.collection("DATA").get();
            return null;
        }
    }).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

            if(task.isSuccessful() && task.isComplete()){

                try{
                    for(QueryDocumentSnapshot document : snapshot.getResult()){
                        states.add(document.getId());
                    }
                    sendResponseToActivity("Success", RESULT_OK);
                } catch (Exception e){
                    e.printStackTrace(); // Transaction is not yet complete
                    sendResponseToActivity("Fail", RESULT_OK);
                }
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if(e.getMessage().contains("UNAVAILABLE"))
                sendResponseToActivity("NoInternet", RESULT_OK);
            else
                sendResponseToActivity("Fail", RESULT_OK);
        }
    });

} // End getStatesList()


from Android - Transaction - Task is not yet complete

No comments:

Post a Comment