【发布时间】:2020-08-19 12:42:12
【问题描述】:
我正在尝试将图像上传到 Firebase 存储,然后将此图像的 URL 发送到 Firebase 数据库。 Uri 是正确的,但是当我尝试在我的对象上设置它时,方法 singleDetection.setImage(imagePath) 没有设置任何内容。这是我的代码:
Bitmap image = detectedFaceItems.get(0).getImage();
StorageReference storageRef = storage.getReference();
StorageReference imagesRef = storageRef.child("2.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
StorageTask<UploadTask.TaskSnapshot> uploadTask = imagesRef.putBytes(data)
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to sent a file", Toast.LENGTH_LONG).show();
}
})
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
【问题讨论】:
-
我不确定
singleDetection.setImage(imagePath)应该做什么。但是如果你Log.i("URL", imagePath),你的 logcat 中会输出什么? -
setImage 只是将字符串设置为对象。 onSuccess 方法内部的 Log.i("URL", imagePath) 和 Log.i("URL", singleDetection.getImage()) 正确返回 url,但外部的 Log.i("URL", singleDetection.getImae()) onSuccess 方法返回 nullPointerException。
-
这是预期的:由于下载 URL 是从服务器检索的,因此需要访问下载 URL 的任何代码都需要在
onSuccess内或从那里调用。见stackoverflow.com/questions/53127996/…
标签: android firebase firebase-realtime-database firebase-storage