How Do I Get Files Synchronized From Firebase In Android?
Solution 1:
There's a bit much going on in your code, so I'm going to focus on one part of it only.
The problem is caused by the fact that Firebase downloads the files from the server asynchronously. And while the file is downloading, instead of blocking your code, it continues to run your code. So if you don't take this asynchronous behavior into account, you'll be merging the files before their data has actually been downloaded.
The easiest way to see what's happening is with a few log statements:
Log.i("Firebase", "Starting downloading from storage");
fileReference.getFile(file).addOnSuccessListener(newOnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@OverridepublicvoidonSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.i("Firebase", "Download done");
}
}).addOnFailureListener(newOnFailureListener() {
@OverridepublicvoidonFailure(@NonNull Exception exception) {
Log.e("Firebase", "Download failed: "+exception.toString());
}
});
Log.i("Firebase", "After starting download from storage");
If you run this code you'll get:
Starting downloading from storage
After starting download from storage
Download done
This is probably not what you expected, but perfectly explains why your merging code fails: the data that it wants to merge is not available yet.
The solution is to change the order in which you invoke the code. After the download of a file is completed, check if that was the final file. If so, start the merge:
for (Iterator<TrackModel> i = trackList.iterator(); i.hasNext(); ) {
TrackModelitem= i.next();
finalStorageReferencefileReference= mStorageRef.child("AudioRecords/" + item.fileName);
finalFilefile=newFile(Environment.getExternalStorageDirectory() + "/MueasycoDownloadedAudios/" + item.fileName);
fileReference.getFile(file).addOnSuccessListener(newOnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@OverridepublicvoidonSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
sizes[counter] = (file.length() - 44) / 2;
counter++;
if (counter == trackList.size()) {
Log.i("Firebase", "Downloads completed");
// TODO: merge the downloaded files here
}
}
}).addOnFailureListener(newOnFailureListener() {
@OverridepublicvoidonFailure(@NonNull Exception exception) {
Log.e("Firebase", "Download failed: "+exception.toString());
}
});
}
Post a Comment for "How Do I Get Files Synchronized From Firebase In Android?"