我正在构建一个聊天应用程序,我具有一个用于加载消息的列表视图设置,并且我具有一个图像选择器设置,可以将图像上传到Firebase并在列表视图中显示。当我上传图片时,我从图片选择器中选择了图片,它成功地上传到了Firestore中,但没有显示,也没有为此创建任何消息对象,这是错误的
2019-02-06 16:32:19.032 3810-5272/com.example.android.debateapp E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object" }}
at com.google.firebase.storage.obfuscated.zzj.zza(com.google.firebase:firebase-storage@@16.0.2:455)
at com.google.firebase.storage.obfuscated.zzj.zza(com.google.firebase:firebase-storage@@16.0.2:3435)
at com.google.firebase.storage.obfuscated.zzc.zza(com.google.firebase:firebase-storage@@16.0.2:65)
at com.google.firebase.storage.obfuscated.zzc.zza(com.google.firebase:firebase-storage@@16.0.2:57)
at com.google.firebase.storage.zzc.run(com.google.firebase:firebase-storage@@16.0.2:68)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
但是如果我上传同一张图片后,图片将成功上传并显示
我对其进行了设置,以便将图像上传到firebase storage,然后以图像URL Database的形式显示在message对象下的实时数据库中
代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String downloadUrl = uri.toString();Log.d("tag", downloadUrl);
FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl);
mMessagedatabaseReference.push().setValue(friendlyMessage);
}
});
答案 0 :(得分:1)
文件上传完成之前,您正在致电getDownloadUrl()
。
putFile()
是异步的,这意味着它会立即返回,并且每当上传完成后,您的回调就会在一段时间后被调用。您的代码假设上传要么立即完成,要么阻止当前线程,直到上传完成。这行不通。
相反,当您知道上传已完成时,应该在回调中调用getDownloadUrl()。
photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String downloadUrl = uri.toString();
Log.d("tag", downloadUrl);
FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl);
mMessagedatabaseReference.push().setValue(friendlyMessage);
}
});
}
});