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

从SQLite读取图片URI无法加载问题求助(硬编码可正常显示)

Fix: ResolveUri Failed on Bad Bitmap Uri When Loading Image from SQLite

Let's get straight to fixing your image display issue— the problem is hiding in your monitorData() method!

The Root Cause

Take a look at how you're adding URIs to your list:

public String monitorData() { 
    ArrayList<String> listData = new ArrayList<>(); 
    Cursor data = mDatabaseHelper.getData(); 
    while(data.moveToNext()){ 
        // You're prepending a newline character to the URI here!
        listData.add("\n" + data.getString(1)); 
    } 
    return listData.get(0); 
}

When you call Uri.parse(monitorData()), you're trying to parse a string like "\ncontent://media/external/images/media/47" instead of a clean, valid URI. That extra \n breaks the URI format, which is exactly why you see the resolveUri failed on bad bitmap uri error.

The Quick Fix

Remove the unnecessary newline character when adding the URI to your list:

public String monitorData() { 
    ArrayList<String> listData = new ArrayList<>(); 
    Cursor data = mDatabaseHelper.getData(); 
    while(data.moveToNext()){ 
        // Add the raw URI without the newline
        listData.add(data.getString(1)); 
    } 
    // Add a safety check to avoid crashes if the database has no data
    return listData.isEmpty() ? null : listData.get(0); 
}

Then update your image loading code to handle potential empty results:

String uriString = monitorData();
if (uriString != null) {
    mImageView.setImageURI(Uri.parse(uriString));
}

Extra Best Practices to Avoid Future Issues

  1. Close Your Cursor Properly: Leaving a Cursor open can cause memory leaks. Modify your monitorData() method to clean up:
public String monitorData() { 
    ArrayList<String> listData = new ArrayList<>(); 
    Cursor data = mDatabaseHelper.getData(); 
    try {
        while(data.moveToNext()){ 
            listData.add(data.getString(1)); 
        }
    } finally {
        // Always close the cursor when you're done with it
        if (data != null) {
            data.close();
        }
    }
    return listData.isEmpty() ? null : listData.get(0); 
}
  1. Validate URIs: If you're ever unsure about a URI string, add a quick check to confirm it's valid before parsing:
if (uriString != null && Uri.parse(uriString).isAbsolute()) {
    mImageView.setImageURI(Uri.parse(uriString));
}

That should get your images showing up as expected!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:09:07