android - Firebase 存储 - 检索和显示图像

标签 android google-cloud-firestore picasso

我正在使用 Firebase 设置个人资料 Activity ,用户可以在其中拍摄图像并将其设置为个人资料照片。当用户选择图片时,它会上传到 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();

如果问题仍然存在,那么我需要知道您在下面一行中获得的image值是多少。

String image = dataSnapshot.child("profileImage").getValue().toString();

关于android - Firebase 存储 - 检索和显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553261/

相关文章:

android - 无法从 Fragment 中的 ViewModel 观察 LiveData

android - 是否可以重置 Android 文件的最后修改日期?

flutter - 如何在Firebase中将数据添加到 map

google-cloud-firestore - Google Cloud Firestore 控制台读取所有文件和费用

javascript - 从 Firestore 文档中读取字段的最简单方法

java - 如何访问Fragment类中的setAdapter?

android - 未使用 Picasso 加载图像,未给出错误

android - android布局中的垂直线穿过 View

android - picasso - 取消启动提取

android - 在 Android 浏览器中获取位置