使用Glide通过Uri加载RoomDB存储的图片时出现NullPointerException
核心错误:Uri构造逻辑错误
你存储到Room中的content://格式Uri本身是合法可用的,错误出现在适配器onBindViewHolder中的Uri解析步骤:Arrays.toString(photos.toArray())会将列表转换为带有左右方括号的字符串(例如合法Uri会被包裹成[content://media/external/images/media/71]),这完全不符合Uri格式规范,是Glide加载失败的直接原因,也会触发后续的空指针异常。
修复代码:
@Override public void onBindViewHolder(@NonNull reminderViewHolder holder, int position) { List<String> photos = rems.get(position).getImages(); // 先判空避免空指针异常 if (photos != null && !photos.isEmpty()) { // 直接取列表中存储的原始Uri字符串,不需要多余的数组转字符串操作 Uri uri = Uri.parse(photos.get(0)); GlideApp.with(hostFragment) .load(uri) .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE)) .into(holder.binding.imageView); } else { // 无图片时设置占位图兜底 holder.binding.imageView.setImageResource(R.drawable.你的占位图资源); } holder.binding.textrow.setText(rems.get(position).getTextRem()); holder.binding.daterow.setText(rems.get(position).getDateRem()); holder.binding.isdone.setChecked(rems.get(position).isDone()); }
其他潜在问题修复建议
1. MediaStore插入结果判空
MediaStore.Images.Media.insertImage插入图片失败时会返回null,直接解析会产生空指针,建议增加兜底逻辑:
public Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); if (path == null) { return Uri.EMPTY; } return Uri.parse(path); }
2. 存储权限适配
Android 10(API 29)及以上版本需要申请READ_EXTERNAL_STORAGE权限,Android 13及以上需要申请READ_MEDIA_IMAGES权限,无权限时Glide无法读取MediaStore路径的图片。
3. Gson反序列化泛型适配
你当前反序列化List的写法存在泛型擦除问题,运行时可能出现类型转换异常,建议指定泛型类型:
@Override public List<String> getImages() { if (super.getImages() == null || super.getImages().isEmpty()) { Type listType = new TypeToken<List<String>>() {}.getType(); super.setImages(new Gson().fromJson(this.images, listType)); } return super.getImages(); }
内容的提问来源于stack exchange,提问作者Spectator
相关产品推荐
相关产品推荐

