首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Firebase存储-检索和显示图像

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

Stack Overflow用户
提问于 2019-06-12 08:39:20
回答 2查看 4.1K关注 0票数 1

我正在使用Firebase设置一个个人资料活动,用户可以拍摄一张图像并将其设置为他们的个人资料照片。当用户选择一张图片时,它被上传到Firebase,然而,当我尝试检索图片并使用毕加索将其放入ImageView中时,它不显示。我仔细检查了我是否调用了正确的UI元素。我认为问题可能出在onDataChanged方法中。代码如下:

代码语言:javascript
复制
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:

代码语言:javascript
复制
    <?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代替毕加索,但仍然有同样的问题。下面是我写的代码

代码语言:javascript
复制
 Glide.with(EditBio.this)
                        .load(image)
                        .apply(new RequestOptions()
                        .placeholder(R.drawable.icon1))
                        .into(editPic);
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56553261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档