谁能帮我解决Glide的问题
我正在给阿姨开发一个应用:应用在Recycler视图里面的卡片视图中显示菜谱,数据来自SQLite DB。
目前图片只是在@drawable里面静态显示。我读到"@drawable "文件夹被编译到apk中,事后无法访问。因此需要在外部存储图片。
DB存储的是文件名。
卡片显示基本信息,当一张卡片被点击时,它会打开另一个显示完整信息的活动。
一切都很完美 除此以外
我显然希望她能够上传图片和添加信息,图片将存储在。"sdcardPicturesRecipes"
在使用推荐的Glide时,Glide报告了以下错误。
class com.bumptech.glide.load.engine.GlideException: Failed to load resource
There were 3 causes:
java.io.FileNotFoundException(/sdcard/Pictures/Recipes/carrot_cake.jpg: open failed: EFAULT (Bad address))
java.io.FileNotFoundException(open failed: EFAULT (Bad address))
java.io.FileNotFoundException(open failed: EFAULT (Bad address))...
如果我使用下面的代码,
String image = "/sdcard/Pictures/Recipes/carrot_cake.jpg"; // hard coded for example
File file = new File( image );
if( file.exists() && file.canRead() )
{
Log.d( TAG, "File exists" );
Glide.with( context ).load( image ).into( foodImage ); // foodImage = ImageView
}
日志显示 "文件存在",然而,Glide无法加载并报告上述错误。
试试这个
File directory = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(directory, "Pictures/Recipes/carrot_cake.jpg");
...
看看这个。
String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Recipes/carrot_cake.jpg";
if( file.exists() && file.canRead() ) {
Log.d( TAG, "File exists" );
Glide.with( context ).load( new File(path)).into( foodImage ); // foodImage = ImageView
}
经过反复研究和推敲 下面的代码为了简洁明了,做了大量修改,显然文件的读取会进入一个自定义对象,并且更新了回收视图的适配器。
File folder = new File( getExternalFilesDir( Environment.DIRECTORY_PICTURES ) + IMAGE_DIR ); // where IMAGE_DIR is the folder you want to save or retrieve files from
File[] fileList = folder.listFiles();
String fileName = fileList[0].getPath();
Glide.with( context ).load( fileName ).into( imageView );
注 getExternalStorageDirectory()等都在API 29中被废弃。
另外你需要添加权限,但这是另一个故事。