首页 > 解决方案 > 避免使用 Recycleview 从 Firebase 重新加载图像

问题描述

我有一个回收视图,它将不同的图像加载到 Firebase 存储中。当我滚动我的回收视图时,它每次都会加载相同的图像(就像回收视图的定义一样)。

我如何一次下载这些图像并附加到我的回收视图,这样它在滚动时不应该重新加载?

我试过这样。

public void onBindViewHolder(final TodaysBdayViewHolder holder, int position)
{
           storageReference=FirebaseStorage.getInstance().getReference().child("profiles/"+contacts.get(position)+".jpg");

            final File localFile=File.createTempFile("profile_pic","jpeg",new File(context.getExternalFilesDir("null").getAbsolutePath()));

            storageReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                    Log.i("app","FinishIntro Img loaded");
                    Bitmap bitmap= BitmapFactory.decodeFile(localFile.getAbsolutePath());
                    holder.FriendPhoto.setImageBitmap(bitmap);
                }
            }).addOnFailureListener(new OnFailureListener() {

                public void onFailure(@NonNull Exception e) {

                }
            });
}

标签: androidfirebaseandroid-recyclerviewfirebase-storage

解决方案


您正在自己从文件中解码位图,这不是很有效。相反,我建议使用旨在有效执行此类操作的库,例如PicassoGlide

毕加索的方法:

添加到gradle:

implementation 'com.squareup.picasso:picasso:2.71828'

并在加载时执行此操作:

//the file  
final File localFile=File.createTempFile("profile_pic","jpeg",new File(context.getExternalFilesDir("null").getAbsolutePath()));


//the reference
storageReference=FirebaseStorage.getInstance().getReference().child("profiles/"+contacts.get(position)+".jpg");

//the call
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
    // use this uri in picasso call into imageview
Picasso.get().load(uri.toString()).into(holder.FriendPhoto);

    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});

推荐阅读