问题
In my android app when I am uploading a PDF file it's uploaded in the firebase storage but the file name and url is not shown in the realtime database.
private void uploadPDFFile(Uri data) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("uploads/"+System.currentTimeMillis()+".pdf");
reference.putFile(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl();
while(!uri.isComplete());
Uri url = uri.getResult();
uploadPDF uploadPDF = new uploadPDF(editPDFName.getText().toString(),url.toString());
databaseReference.child(databaseReference.push().getKey()).setValue(uploadPDF);
Toast.makeText(MainActivity.this, "File uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded: " + (int) progress + "%");
}
});
}
回答1:
Don't do this please:
while(!uri.isComplete());
Even if it works, it's a tight loop consuming more resources than needed.
Instead follow the pattern shown in the Firebase documentation on getting a download URL:
reference.putFile(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
uriTask.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Uri url = uriTask.getResult();
uploadPDF uploadPDF = new uploadPDF(editPDFName.getText().toString(),url.toString());
databaseReference.child(databaseReference.push().getKey()).setValue(uploadPDF);
Toast.makeText(MainActivity.this, "File uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
}
}).addOnProgressListener(
来源:https://stackoverflow.com/questions/56823096/file-uploaded-but-not-shown-in-the-firebase-realtime-database-android-studio