Android Studio의 Firebase 데이터베이스에서 이미지를 검색하는 데 문제가 있습니다.

Aug 17 2020

나는 자바로 안드로이드 스튜디오에서 채팅 앱을 만들려고 노력하고 있습니다. 이미지를 업로드하고 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();
}

}

답변

Nik Aug 17 2020 at 22:07

먼저 URL이 제대로 생성되지 않으면 URL이 다른 방식으로 생성되는 것과 같이 URL이 다르게 생성되기 때문에 데이터베이스에 대한 URL을 확인하십시오.

  1. 데이터베이스에서 이미지 경로를 복사하고 URL이 유효한지 브라우저에서 테스트합니다.
  2. 글라이드 라이브러리를 사용하십시오. 피카소보다 더 효율적입니다

Glide.with (yourContext) .load (url) .centerCrop (). placeholder (R.drawable.loading_spinner) .into (yourImageView)

  • 참고 centreCrop () 및 placeHolder ()는 선택 사항이며 원하는 경우 제거 할 수 있습니다. https://github.com/bumptech/glide