当本地存储中不存在文件时,毕加索显示错误的图像

时间:2019-06-11 14:14:11

标签: android android-recyclerview picasso

我有一个回收站视图,其中显示了具有化身的用户列表。登录后,我下载了所有头像,并使用mongo db中用户行ID的文件名将其保存在本地。当头像文件在存储中不可用时,毕加索会随机加载其他用户的头像之一。我应该怎么做才能避免这种情况。 这是在不可用时显示或下载图像的常用代码

我尝试在毕加索中使用缓存策略,但这也不起作用。

public ImageUtils loadFromDisk(String id, ImageView target) {
        Log.d(TAG, "loadFromDisk: imageId: " + id);
        File directory = contextWrapper.getDir("avatars", Context.MODE_PRIVATE);
        File avatarPath = new File(directory, id);
        if (avatarPath.exists()) {
            Log.d(TAG, "loadFromDisk: loaded from disk" + avatarPath);
            Picasso.get().load(avatarPath)
                    .memoryPolicy(MemoryPolicy.NO_CACHE)
                    .networkPolicy(NetworkPolicy.NO_CACHE)
                    .into(target);
        } else {
           Picasso.get().load(R.drawable.image_thumb).into(target);
        }
        return this;
    }

我从RecyclerView bindView持有人类的Singleton ImageUtils类调用loadFromDisk。

PS:bindViewHolder代码

public void onBindViewHolder(@NonNull RecentChatsViewHolder recentChatsViewHolder, int i) {
        Log.d(TAG, "onBindViewHolder: content row");

        if (recentChat.isNew) {
            recentChatsViewHolder.blueDot.setVisibility(View.VISIBLE);
        } else {
            recentChatsViewHolder.blueDot.setVisibility(View.GONE);
        }

        recentChatsViewHolder.avatar.setImageResource(R.drawable.ic_info_outline_white_48dp);
        ImageUtils.getInstance(context).loadFromDisk(recentChat.id, recentChatsViewHolder.avatar); //this calls above function here I don't pass the else condition of above method so there's no race condition 

    }

1 个答案:

答案 0 :(得分:0)

由于这是在recyclerView内部,因此我假设正在发生某种竞赛情况。当您致电FileDownloader下载一些图片时。它下载图像并将其加载到目标。但是目标不正确,因为现在滚动了回收站视图。

也许,可以通过将id作为标签添加到ImageView并在下载图像后检查该标签来避免这种情况。如果标签不同,请不要将图像加载到视图中。 ->仅当下载回调/ lambda通过id时,此方法才有效。

编辑:

我不知道fallback发生了什么。如果您可以将其从添加的代码段中删除,那会更好。

我可以建议两件事。

  1. ImageView.setImageBitmap(null)或要求Picasso在加载新图像之前清除目标。如果头像不存在,请清除目标。
  2. 添加errorDrawable,以便在出现错误时不会显示前一张图片。