android - Firebase 存储 - 检索和显示图像
问题描述
我正在使用 Firebase 设置个人资料活动,用户可以在其中拍摄图像并将其设置为他们的个人资料图片。当用户选择一张图片时,它会上传到 Firebase,但是,当我尝试检索图片并使用 Picasso 将其放入 ImageView 时,它没有显示出来。我已经仔细检查了我正在调用正确的 UI 元素。我相信问题可能出在 onDataChanged 方法中。这是代码:
public class EditBio extends AppCompatActivity {
ImageView editPic;
EditText editUsername;
EditText editAge;
EditText editBio;
Button save;
private FirebaseAuth mAuth;
private DatabaseReference usersRef;
private ProgressDialog loadingBar;
private StorageReference UserProfileImageRef;
String currentUserId;
final static int galleryPic = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_bio);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profile Images");
editPic = findViewById(R.id.add_profile_pic);
editUsername = findViewById(R.id.edit_username);
editAge = findViewById(R.id.edit_age);
editBio = findViewById(R.id.edit_bio);
save = findViewById(R.id.save_profile);
loadingBar = new ProgressDialog(this);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveAccountInformation();
Intent intent = new Intent(EditBio.this, Profile.class);
startActivity(intent);
}
});
editPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//send user to phone gallery
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, galleryPic);
}
});
usersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String image = dataSnapshot.child("profileImage").getValue().toString();
//use Picasso to insert image
Picasso.get()
.load(image)
.placeholder(R.drawable.icon1)
.into(editPic);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
//Function to select and crop an image from gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == galleryPic && resultCode == RESULT_OK && data!=null){
Uri imageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK){
//store image in firebase storage
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait while we update your profile image");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserId + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(EditBio.this, "Profile image saved successfully", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
usersRef.child("profileImage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
//Intent intent = new Intent(EditBio.this, Profile.class);
//startActivity(intent);
Toast.makeText(EditBio.this, "Profile image stored to firebase database successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String message = task.getException().getMessage();
Toast.makeText(EditBio.this, "Error occured when saving profile: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
});
}
else {
Toast.makeText(this, "Error occured: Image cant be cropped. Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
//store account information in firebase
private void saveAccountInformation(){
String username = editUsername.getText().toString();
String age = editAge.getText().toString();
String bio = editBio.getText().toString();
if (TextUtils.isEmpty(username)){
Toast.makeText(this, "Please enter a user name", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(age)){
Toast.makeText(this, "Please enter an age", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(bio)){
Toast.makeText(this, "Please enter a bio", Toast.LENGTH_SHORT).show();
} else {
loadingBar.setTitle("Saving Information");
loadingBar.setMessage("Please wait while we update your account information");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
HashMap userMap = new HashMap();
userMap.put("username", username);
userMap.put("age", age);
userMap.put("bio", bio);
usersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()){
SendUserToProfileActivity();
Toast.makeText(EditBio.this, "Your account information has been saved", Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
else{
String message = task.getException().getMessage();
Toast.makeText(EditBio.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
//send user to profile activity
private void SendUserToProfileActivity(){
Intent profileIntent = new Intent(this, Profile.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(profileIntent);
finish();
}
}
布局.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EditBio"
android:background="@drawable/gradient">
<ImageView
android:id="@+id/add_profile_pic"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:layout_marginTop="15dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_username"
android:layout_below="@+id/add_profile_pic"
android:layout_marginTop="80dp"
android:background="@drawable/circle"
android:textColorHint="@color/colorPrimary"
android:hint="Username: "/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_age"
android:layout_below="@+id/edit_username"
android:layout_marginTop="30dp"
android:background="@drawable/circle"
android:textColorHint="@color/colorPrimary"
android:hint="Age: "/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_bio"
android:layout_below="@+id/edit_age"
android:layout_marginTop="30dp"
android:background="@drawable/circle"
android:textColorHint="@color/colorPrimary"
android:hint="Bio: "/>
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="@+id/save_profile"
android:layout_below="@+id/edit_bio"
android:background="@drawable/circle"
android:layout_marginTop="99dp"
android:text="Save"
android:textColor="@color/colorPrimary"
android:layout_centerInParent="true"/>
</RelativeLayout>
编辑我尝试使用 Glide 而不是 Picasso,但我仍然遇到同样的问题。这是我写的代码
Glide.with(EditBio.this)
.load(image)
.apply(new RequestOptions()
.placeholder(R.drawable.icon1))
.into(editPic);
解决方案
而不是使用这条线将上传的图像存储到firebase数据库中,
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
用这个,
final String downloadUrl = task.getDownloadUrl().toString();
如果问题仍然存在,那么我需要知道您在下面的行中获得了什么图像值。
String image = dataSnapshot.child("profileImage").getValue().toString();
推荐阅读
- python - 如何在 Tensorflow 中为数组创建 np.subtract.outer
- r - 去掉向量字符串元素中空格后的部分
- microphone - 我可以通过 USB 接口访问多少个音频通道?全部 7 个?或混合到1?
- flutter - 在我的布局中显示分隔线时出现问题
- django - “如何使用父类从 django 多对多字段的模板中获取查询??”
- java - Java - 以编程方式提取子字符串
- c# - 如何在 Visual Studio 中使用安装项目安装程序在 IIS 中发布 asp Web 应用程序
- office365 - 使用 displayDialogAsync 时“{0} 想要显示一个新窗口”
- python - 如何在python的下一行打印列表的每个值
- javascript - 如何发布提及以松弛传入的 webhook