You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Picasso加载RecyclerView图片,重启应用后图片消失显示占位图

问题:RecyclerView中头像重启后无法保留,仅显示占位图

我在RecyclerView中添加头像后,头像能和对应用户名一同显示,但重启或终止应用后,已加载的头像会被占位图取代,无法保留。但在编辑对话框中打开时头像能正常保留,问题仅出在RecyclerView的onBindViewHolder方法中。

我的onBindViewHolder代码:

protected void onBindViewHolder(@NonNull myViewHodler holder, int position, @NonNull AddStudent model) {

    holder.sName.setText(model.studentFullname);
    holder.sEmail.setText(model.studentEmail);
    holder.sAge.setText(model.studentAge);

    Picasso.get()
            .load(model.studentImage)
            .placeholder(R.drawable.defprofile)
            .transform(new CropCircleTransformation())
            .into(holder.imgStudent);
}

我的AddStudent Model类代码:

package com.example.attendancechecker_application;

public class AddStudent {
    public String studentFullname, studentEmail, studentAge, studentImage;

    public AddStudent(){

    }

    public AddStudent(String studentFullname, String studentEmail, String studentAge, String studentImage){ //String getPassword
        this.studentFullname = studentFullname;
        this.studentEmail = studentEmail;
        this.studentAge = studentAge;
        this.studentImage = studentImage;
    }
}
问题原因及解决办法

核心原因

  1. Picasso缓存机制问题:默认内存缓存会在应用重启后清空,若studentImage是网络URL,重启后需重新下载;若网络请求失败或URL无效,就会显示占位图。如果是本地路径,可能是临时文件被清理,导致路径失效。
  2. 数据持久化缺失:studentImage字段未正确保存到本地存储(如数据库、SharedPreferences),重启后加载的AddStudent数据中该字段为空或无效,导致Picasso加载失败。

具体解决步骤

1. 优化Picasso缓存策略,优先读取磁盘缓存

修改加载代码,让Picasso先尝试从磁盘缓存读取,失败再走网络,确保重启后能快速加载缓存的图片:

Picasso.get()
        .load(model.studentImage)
        .placeholder(R.drawable.defprofile)
        .transform(new CropCircleTransformation())
        .networkPolicy(NetworkPolicy.OFFLINE) // 先离线加载磁盘缓存
        .into(holder.imgStudent, new Callback() {
            @Override
            public void onSuccess() {}

            @Override
            public void onError(Exception e) {
                // 离线加载失败,再发起网络请求
                Picasso.get()
                        .load(model.studentImage)
                        .placeholder(R.drawable.defprofile)
                        .transform(new CropCircleTransformation())
                        .into(holder.imgStudent);
            }
        });

2. 确认studentImage字段的持久化正确性

  • 如果用云端存储(如Firebase),检查数据是否正确保存,重启后model.studentImage能否获取到有效URL。
  • 如果是本地图片,确保存储的是应用私有目录下的永久路径,而非临时缓存路径,且重启后文件仍存在。
  • 检查RecyclerView的数据加载逻辑,确认初始化时从持久化存储读取的AddStudent列表中,studentImage字段不为空或无效值。

3. 对比编辑对话框的加载逻辑

编辑对话框能正常显示头像,说明该场景下studentImage是有效的,且加载逻辑可能更完善。对比两者的代码,排查RecyclerView是否存在数据加载不完整的情况。

内容的提问来源于stack exchange,提问作者compsci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 00:45:30