我正在制作一个显示用户个人资料信息的Android应用。我可以将图像存储在Cloud Storage上,但是我不确定如何检索和显示存储在Cloud Storage中的用户特定图像。
我面临的主要问题之一是user.getPhotoUrl()
没有给我正确的uri。它给了我com.google.android.gms的形式。等等。
我尝试使用Glide来显示图像。但是,由于我收到FileNotFoundException,所以它不起作用。因此,我尝试将Glide与StorageReference结合使用。
但是,使用StorageReference的问题在于,当我想检索特定于用户的图像时,必须明确提供图像的uri。
我希望用户选择的个人资料图片显示在个人资料页面上,但是当我在Android Studio上运行该应用程序时,没有任何显示。
答案 0 :(得分:0)
我写了一种方法,可以将位图上传到android的firebase存储中并获取url,请使用该方法上传图片并获取url,之后,如果遇到任何问题,请告诉我。
public static void UploadBitmap(Activity activity, Bitmap bitmap, String serverFileName) {
if (bitmap == null) {
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
// Create a reference to the file you want to upload
String directory = "images/";
StorageReference fileRef = storageRef.child(directory + serverFileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
UploadTask uploadTask = fileRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
Log.e("oops","error in bitmap uploading");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
// now download url first
}
});
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 fileRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String stringUrl = downloadUri.toString();
// Great image is uploaded and url is here, you can load image anywhere via this stringUrl with Glide or Picasso.
} else {
// Handle unsuccessful uploads
Log.e("oops","error in url retrieval");
}
}
});
}
});
}
});
thread.start();
}