提问者:小点点

android studio中从firebase数据库中检索图像的问题


我一直在尝试和Java一起在Android Studio做一款聊天应用。我已经成功地编写了代码上传一个图像,并将它从Firebase存储转移到Firebase数据库。当我试图用毕加索的方法检索图像时,我试图这样做的图像视图会变得不可见。

private Button UpdateAccountSettings;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private StorageReference UserProfileImagesRef;
private static final int GalleryPic = 1;
private ProgressDialog loadingBar;
private String photoUrl;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();
    RootRef = FirebaseDatabase.getInstance().getReference();
    UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");

    InitializeFields();

   userProfileImage.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v)
       {
            Intent galleryIntent = new Intent();
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GalleryPic);
       }
   });



    UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            UpdateSetting();
        }
    });


    RetrieveUserInfo();

}



private void InitializeFields() {

    UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
    userName = (EditText) findViewById(R.id.set_user_name);
    userStatus = (EditText) findViewById(R.id.set_profile_status);
    userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
    loadingBar = new ProgressDialog(this);

}

@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)
                {



                    loadingBar.setMessage("Uploading Image");
                    loadingBar.setCanceledOnTouchOutside(false);
                    loadingBar.show();

                     Uri resultUri = result.getUri();


                    StorageReference filepath = UserProfileImagesRef.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(SettingsActivity.this, "Profile Image Saved Successfully...", Toast.LENGTH_SHORT).show();
                                loadingBar.dismiss();

                                String downloadUrl = task.getResult().getDownloadUrl().toString();

                                RootRef.child("Users").child(currentUserID).child("image")
                                        .setValue(downloadUrl)
                                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task)
                                            {
                                                if (task.isSuccessful())
                                                {
                                                    loadingBar.dismiss();
                                                }
                                                else
                                                {
                                                    String message = task.getException().toString();
                                                    Toast.makeText(SettingsActivity.this, "Error : " + message, Toast.LENGTH_SHORT).show();
                                                    loadingBar.dismiss();
                                                }
                                            }
                                        });
                            }
                            else
                            {
                                String message = task.getException().toString();
                                Toast.makeText(SettingsActivity.this, "Error : " + message, Toast.LENGTH_SHORT).show();
                                loadingBar.dismiss();
                            }

                        }
                    });
                }
    }

}

private void UpdateSetting() {
    String setUserName = userName.getText().toString();
    String setStatus = userStatus.getText().toString();

    if (TextUtils.isEmpty(setUserName)) {
        AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
        builder.setCancelable(true);
        builder.setTitle("Error");
        builder.setMessage("Please write a user name");
        builder.setNegativeButton("Back", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    } else if (TextUtils.isEmpty(setStatus)) {
        AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
        builder.setCancelable(true);
        builder.setTitle("Error");
        builder.setMessage("Please write a Status");
        builder.setNegativeButton("Back", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();

    } else {
        HashMap<String, String> profileMap = new HashMap<>();
        profileMap.put("uid", currentUserID);
        profileMap.put("name", setUserName);
        profileMap.put("status", setStatus);
        profileMap.put("image", photoUrl);
        RootRef.child("Users").child(currentUserID).setValue(profileMap)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            SendUserToMainActivity();
                            Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();

                        }
                        else
                            {

                            String message = task.getException().toString();
                            Toast.makeText(SettingsActivity.this, "Error :" + message, Toast.LENGTH_SHORT).show();

                        }
                    }

                    ;
                });
    }
}



private void RetrieveUserInfo()
{
    RootRef.child("Users").child(currentUserID)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                {
                    if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image"))))
                    {
                        String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                        String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
                        String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();

                        userName.setText(retrieveUserName);
                        userStatus.setText(retrieveUserStatus);
                        photoUrl = retrieveProfileImage;
                        Picasso.get().load(retrieveProfileImage).into(userProfileImage);


                    }
                    else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
                    {
                        String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                        String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();

                        userName.setText(retrieveUserName);
                        userStatus.setText(retrieveUserStatus);
                    }
                    else
                    {
                        Toast.makeText(SettingsActivity.this, "Please Set Your Profile Info...", Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError)
                {

                }
            });
}



private void SendUserToMainActivity()
{
    Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(mainIntent);
    finish();
}

}


共1个答案

匿名用户

首先,检查您的URL是否进入数据库,因为有时URL会产生不同的结果,比如如果没有正确地生成URI,那么URL会以不同的方式生成

  1. 从数据库复制图像路径并在浏览器上测试URL是否有效
  2. 使用滑动库。比毕加索更有效率

Glide.with(yourContext)。Load(url).CenterCrop()。Placeholder(r.Drawable.Loading_Spinner)。Into(yourImageView)

  • 注意centreCrop()和placeHolder()是可选的,如果需要,您可以删除,有关更多信息,请参阅https://github.com/bumptech/glide