我正在将pdf上传到Firebase存储,并希望获得其下载网址。我使用以下代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1212:
if (resultCode == RESULT_OK) {
String FilePath = data.getDataString();
t.setText(FilePath);
Uri pdfuri = data.getData();
final StorageReference mp = mpdf.child("pdf").child(random()+".pdf");
mp.putFile(pdfuri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
{
String download_url = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
String parent = getIntent().getStringExtra("type").toString();
String ch = getIntent().getStringExtra("value").toString();
GeologicDatabase.modifySingle(parent,ch,download_url);
Toast.makeText(modifypdf.this,download_url , Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(modifypdf.this,"Faild" , Toast.LENGTH_SHORT).show();
}
}
});
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
这条线的结果
String download_url = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
是“com.google.android.gms.tasks.zzu@7f93358”不是正确的网址
该问题的解决方案是使用上传任务,并在其完整侦听器中编写代码,将任务结果作为Uri并将其转换为字符串
final String name = random() + ".pdf";
dp = mpdf.child("pdf").child(name);
UploadTask uploadTask = dp.putFile(pdfuri);
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return dp.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
tt = title.getText().toString();
Uri downloadUri = task.getResult();
String download_url = downloadUri.toString();
String parent = getIntent().getStringExtra("type").toString();
String ch = getIntent().getStringExtra("value").toString();
GeologicDatabase.updateChild(parent, ch, "url",download_url,tt);
GeologicDatabase.updateChild(parent,ch,"name",name,tt);
Toast.makeText(addpdf.this, download_url, Toast.LENGTH_SHORT).show();
finish();
} else {
// Handle failures
// ...
}
}
});
getDownloadUrl()不返回URL。从the javadoc可以看出,它返回一个产生URL的Task。您必须等待此任务完成才能获得最终的URL。
//试一下
Task<Uri> newTask = task.getResult().getMetadata().getReference().getDownloadUrl();
newTask.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
yourUriVariable= uri;
}
});