从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
- 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); }
- 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
相关产品推荐
相关产品推荐

