Firebase存储 - 检索和显示图像

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (3)

我正在使用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();
    }

}

layout.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>
提问于
用户回答回答于

您的链接格式不正确,请尝试将https添加到您的链接:

          Picasso.get()
               .load("https://"+image)
               .placeholder(R.drawable.icon1)
               .into(editPic);
            }

注意

有时Picasso在处理firebase和https图像时遇到一些问题,我建议你使用Glide

扫码关注云+社区

领取腾讯云代金券