【问题标题】:How to return a boolean value when a file is successfully uploaded inside onSuccessListener?当文件在 onSuccessListener 中成功上传时如何返回布尔值?
【发布时间】:2020-04-26 17:24:04
【问题描述】:

先看看这个。我在 submitProfile()

中调用了一个函数 uploadUserPdf()
public void submitProfile() {
     if(!uploadUserPdf()) {
          return;
     }
     else {
        //...............
     }
}

这是 uploadUserPdf() 函数

private boolean uploadUserBiodataPdf() {
        Uri fileUri = Uri.parse(Pdf);
        final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Pictures");
        StorageReference pdfRef = storageReference.child(mUser.getUid()).child(fileUri.getLastPathSegment());

        pdfRef.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                pdfRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        Pdf = uri.toString();
                        Toast.makeText(ContinueProfile.this, "Pdf Uploaded", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
        return false;
    }

我想如果文件上传成功则返回 true。但是我找不到任何空间来写return true。文件上传成功是否可以返回真值??

【问题讨论】:

  • 看看this。您可以使用回调来调用/返回真或假

标签: android firebase firebase-storage


【解决方案1】:

将文件上传到 Firebase 存储是异步进行的,因为这可能需要一些时间。在后台进行上传时,您的主代码继续在前台执行。然后当上传完成时,你的onSuccess 会被调用。

这意味着当你的return false 运行时,你的onSuccess 方法都没有被调用。而且您不能返回现在尚未发生的事情。

因此,任何需要下载 URL 的代码都需要在从服务器检索到下载 URL 时调用的 onSuccess 方法中。就像你的 Toast,它在正确的时间运行。

如果您想将使用下载 URL 的代码与生成它的代码分开,您可以传入一个自定义回调接口,然后在获取下载 URL 时调用它:

public interface GetDownloadUrlCallback {
  void onCallback(String uri);
}
private boolean uploadUserBiodataPdf(GetDownloadUrlCallback callback) {
    Uri fileUri = Uri.parse(Pdf);
    final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Pictures");
    StorageReference pdfRef = storageReference.child(mUser.getUid()).child(fileUri.getLastPathSegment());

    pdfRef.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            pdfRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    callback(uri.toString());
                }
            });
        }
    });

然后调用它:

GetDownloadUrlCallback(new GetDownloadUrlCallback() {
  @Override
  public void onCallback(String uri) {
    Log.i("GetDownloadUrlCallback", "Got uri: "+uri);
  }
});

另见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多