gpt4 book ai didi

android - onSuccessListener中文件上传成功时如何返回 bool 值?

转载 作者:行者123 更新时间:2023-12-01 17:06:47 27 4
gpt4 key购买 nike

首先看这个。我在 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。文件上传成功是否可以返回真值??

最佳答案

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

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

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

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

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);
}
});

另请参阅:

关于android - onSuccessListener中文件上传成功时如何返回 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61457351/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com