Android中如何在ListView项的ImageView显示SQLite数据库Blob图片
解决SQLite Blob图片在ListView的ImageView中显示的问题
看起来你已经搞定了文本数据的读取,就差Blob图片的显示了,核心逻辑就是把Blob字节数组转换成Bitmap,再设置到ImageView里。我帮你梳理下具体步骤和修改后的代码:
第一步:完善Histoire数据模型类
首先要让Histoire类能处理图片转换逻辑,添加Bitmap字段来存储转换后的图片:
public class Histoire { private int idHistoire; private int nombredepages; private String titre; private String auteur; private byte[] imageBlob; private Bitmap imageBitmap; // 新增:存储转换后的Bitmap // 调整构造方法,传入Blob后自动完成转换 public Histoire(int idHistoire, int nombredepages, String titre, String auteur, byte[] imageBlob) { this.idHistoire = idHistoire; this.nombredepages = nombredepages; this.titre = titre; this.auteur = auteur; this.imageBlob = imageBlob; // 将Blob字节数组转换为Bitmap if (imageBlob != null && imageBlob.length > 0) { ByteArrayInputStream stream = new ByteArrayInputStream(imageBlob); // 可选:添加图片压缩避免内存溢出,这里设置采样率为2(宽高缩小为原来的1/2) BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; this.imageBitmap = BitmapFactory.decodeStream(stream, null, options); } } // 新增Bitmap的getter方法,供Adapter调用 public Bitmap getImageBitmap() { return imageBitmap; } // 保留你原有的其他getter方法:getIdHistoire()、getTitre()、getAuteur()、getNombredepages() }
第二步:修正DatabaseHelper的数据读取逻辑
你原来的代码里已经生成了Bitmap,但没有赋值给Histoire对象,现在去掉冗余代码,直接利用Histoire的构造方法完成转换:
public List<Histoire> getListHistoire() { Histoire histoire = null; List<Histoire> histoirelist = new ArrayList<>(); openDatabase(); Cursor cursor = mDatabase.rawQuery("SELECT * FROM histoire", null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { // 直接传入Blob字段,由Histoire构造自动完成图片转换 histoire = new Histoire( cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getString(3), cursor.getBlob(4) ); histoirelist.add(histoire); cursor.moveToNext(); } cursor.close(); closeDatabase(); return histoirelist; }
第三步:在ListHistoireAdapter中设置图片到ImageView
现在只需要在getView方法里获取Histoire对象的Bitmap,设置给对应的ImageView即可:
@Override public View getView(int position, View convertView, ViewGroup parent) { View v = View.inflate(mContext, R.layout.activity_item_histoire, null); TextView tvtitre = (TextView)v.findViewById(R.id.txtTitle); TextView tvauteur = (TextView)v.findViewById(R.id.txtAuteur); TextView tvnb = (TextView)v.findViewById(R.id.txtnb); ImageView tvimg=(ImageView)v.findViewById(R.id.imgIcon); Histoire currentStory = mHistoireList.get(position); tvtitre.setText(currentStory.getTitre()); tvauteur.setText(currentStory.getAuteur()); tvnb.setText(String.valueOf(currentStory.getNombredepages())); // 核心:设置图片到ImageView Bitmap storyImage = currentStory.getImageBitmap(); if (storyImage != null) { tvimg.setImageBitmap(storyImage); } else { // 如果没有图片,设置一张默认占位图(记得在drawable目录添加对应的图片资源) tvimg.setImageResource(R.drawable.default_story_image); } return v; }
额外优化建议
如果你的图片尺寸较大,频繁创建Bitmap可能会导致内存问题,推荐:
- 使用ViewHolder模式复用ListView的Item视图,减少重复创建View的开销
- 可以考虑在后台线程完成Blob到Bitmap的转换(比如用Coroutines或者AsyncTask),避免阻塞主线程
内容的提问来源于stack exchange,提问作者chiraz ch
相关产品推荐
相关产品推荐

