文件已上传但未显示在Firebase实时数据库中-Android Studio

时间:2019-06-30 07:16:16

标签: java android firebase-realtime-database google-cloud-storage firebase-storage

在我的Android应用中,当我上传PDF文件时,它已上传到Firebase存储器中,但文件名和网址未显示在实时数据库中。

 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 个答案:

答案 0 :(得分:0)

请不要这样做:

while(!uri.isComplete());

即使可行,这也是一个循环,消耗的资源超过了需要。

请遵循getting a download URL上Firebase文档中显示的模式:

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(