As I'm going through Firebase Storage and Database tutorials for Android, I came across to a problem to prioritize the queries.
I need to save a visitor data into Firestore Database
and an image of a visitor in the Firebase Storage
with a single button click. So, I have the following java method in Android:
public void saveNewVisitor() {
Uri file = Uri.fromFile(new File(image_path));
StorageReference imageRef = storageRef.child("images/"+file.getLastPathSegment());
UploadTask uploadTask = imageRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
downloadURL = taskSnapshot.getDownloadUrl();
}
});
//-----------------------------------
Map<String, Object> dataToSave = new HashMap<String, Object>();
dataToSave.put(NAME, visitorName);
dataToSave.put(AGE, visitorAge);
dataToSave.put(GENDER, visitorGender);
dataToSave.put(IMAGE_URL, String.valueOf(downloadURL));
CollectionReference mColRef = FirebaseFirestore.getInstance().collection("visitors");
mColRef.add(dataToSave).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "Visitor has been saved!");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding a visitor", e);
}
});
}
In the above code, there are two actions happening. In the first part, an image is being saved in Firebase Storage and in OnSuccessListener
it's generating URL
to download that image for the future use. In the second part, the text data, including above generated URL is being saved in the Database.
So, the problem is, Android and Firebase is executing text data query first, then executing image saving query. This is resulting in URL = null
in database as at the time of saving the data downloadURL = null
.
My question is how to prioritize image saving query as HIGH to make sure it'll be executed before text data saving query. Firebase documents aren't that clear on this topic. Any kind of help or suggestion to resolve the problem is appreciated.