Невозможно загрузить изображения из хранилища Firebase - PullRequest
0 голосов
/ 04 июля 2019

Я пытаюсь загрузить изображение профиля из firebase, имя которого установлено в качестве идентификатора пользователя пользователя.Я использую библиотеку glide для загрузки изображений, но получаю ошибку StorageException: StorageException has occurred. Object does not exist at location..

Вот мой код

String uid = user.getUid();

            storageReference.child("ProfilePictures").child(uid).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    // Got the download URL for 'users/me/profile.png'
                    Log.d("TAG" , "URI = "+uri);

                    GlideApp.with(context).load(uri).into(profilepic);
                    //profilepic.setImageURI(uri);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle any errors
                    Toast.makeText(getApplicationContext(), "Error getting Profile Picture", Toast.LENGTH_LONG).show();
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}

    });

Моя база данных enter image description here

enter image description here

Декларация о храненииСсылка

StorageReference storageReference;

storageReference = FirebaseStorage.getInstance().getReference();

Ответы [ 3 ]

2 голосов
/ 04 июля 2019

Убедитесь, что пользователям разрешен доступ к хранилищу с этим правилом:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if true;
    }
  }
}

Поместите это в свои зависимости:

dependencies {
    // FirebaseUI Storage only
    implementation 'com.firebaseui:firebase-ui-storage:4.3.1'
}

Теперь получить изображение из хранилища:

StorageReference storageReference= FirebaseStorage.getInstance().getReference().child("ProfilePictures/"+uid+".jpg"); // if you know how to use this you can get image directly without doing that big query

//Following line will be useful when you try to get image from storage
GlideApp.with(this /* context */)
        .load(storageReference)
        .into(imageView);

Для получения дополнительной информации вы можете прочитать документы или просто прокомментировать меня, если возникнет какая-либо проблема

2 голосов
/ 04 июля 2019

Измените это:

storageReference.child("ProfilePictures").child(uid).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override

на это:

storageReference.child("ProfilePictures").child(uid + ".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
1 голос
/ 05 июля 2019
 public StorageReference mStorageRef;
 StorageReference particular_image;

 private FirebaseDatabase firebasedatabase;
 private DatabaseReference databasereference;

 oncreate()
   {
     mStorageRef = FirebaseStorage.getInstance().getReference().child("give");
     firebasedatabase = FirebaseDatabase.getInstance();  //1st time is imp.
     databasereference = firebasedatabase.getReference().child("giver_data"); 

      particular_image.putFile(photoURI).addOnSuccessListener
                (this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        final Uri download_uri = taskSnapshot.getDownloadUrl();
                            Glide.with(getApplicationContext())
                .load(p_l.getPhotoUrl()).asBitmap().override(view.getMaxWidth(),view.getMaxHeight()).error(R.drawable.ic_selfie_point_icon)   //asbitmap after load always.
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        Bitmap d = new BitmapDrawable(resource).getBitmap();
                        int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
                        Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
                        //holder.food_img.setImageBitmap(scaled);
                        view.setImageBitmap(scaled);
                    }
                });
                   //getting uri of the image stored
                      //Photo_link p_link =newPhoto_link(download_uri.toString());
                     //  databasereference.push().setValue(p_link);
                        //String uri_string = download_uri.toString();

                        pb.clearAnimation();
                        pb.clearFocus();
                       // animation.end();
                        Intent i = new Intent(getApplicationContext(),Giver_Edit.class);
                        i.setData(download_uri);
                        startActivity(i);

                        Toast.makeText(getApplicationContext(),"Food Image Uploaded successfully",Toast.LENGTH_SHORT).show();

                        Log.d("giver_image_success","no eroooooor_on_success");
                        //Toast.makeText(getApplicationContext(),"Image added",Toast.LENGTH_LONG).show();
                    }
                });


        //  final Uri selectedImgUri = getIntent().getData();


        particular_image.putFile(uri).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d("giver_image_failure","eroooooor_on_ffailure");
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

И теперь это должно решить вашу проблему! Обязательно проголосуйте, если будете полезны, и прокомментируйте, если сомневаетесь!
Примечание: Вместо функции моего кода UploadTask используйте функцию onSuccess (), которую вы упомянули в коде.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...