Android Error: java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
16lz
2021-01-23
一:Glide有时会出现这样的异常:
java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity at com.bumptech.glide.manager.RequestManagerRetriever.assertNotDestroyed(RequestManagerRetriever.java:134) at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:102) at com.bumptech.glide.Glide.with(Glide.java:653)
原因是:
当你的Activity重新创建并且Glide中的context是旧的时,这个问题最容易发生。例如当你有一个CustomAdapter(ArrayList list, Context context),并且在MainActivity或Fragment重新创建时,你不会将新的context传递给适配器。然后Glide告诉你我正在使用的context对象不再存在。
假如你在一个页面的adapter中加载了100个图片,没加载完finish了,下次再进这个页面会根据缓存在上个acitvity地址加载图片,但上个地址已经被干掉了(finish)。
二:解决方案:
2.1 使用控件的context代替我们传递给adapter的context:
Glide.with(holder.itemView.getContext()) .load(URL) .skipMemoryCache(true) .placeholder(R.drawable.bg_loading_small) .error(R.drawable.bg_loading_small) .into(nativeAdContentImg)
但经过测试,这样做还是不能根本解决问题,有时还是会出现这个异常导致崩溃:最终经过测试发现getApplicationContext()代替掉context比较稳妥
Glide.with(getApplicationContext()) .load(URL) .skipMemoryCache(true) .placeholder(R.drawable.bg_loading_small) .error(R.drawable.bg_loading_small) .into(nativeAdContentImg)
但是 glide加载图片如果用applicationContext的话,会出现当你离开这个页面时,图片的下载工作还在进行,会造成多余的资源消耗,所以可以这样处理,
// 重写activity的onDestroy()方法,停止该页面的glide的加载请求@overrideprotected void onDestroy() { super.onDestroy(); Glide.with(getApplicationContext()).pauseRequests();}
如果是在actiity中做glide加载的话,可以做如下判断:
if (!YourActivity.this.isFinishing()) { Glide.with(YourActivity.this) .load(URL) ...}
2.2 在每次加载图片的时候判断一下context是否为空
final Context context = getContext();if (isValidContextForGlide(context) { // Load image via Glide lib using context} public static boolean isValidContextForGlide(final Context context) { if (context == null) { return false; } if (context instanceof Activity) { final Activity activity = (Activity) context; if (activity.isDestroyed() || activity.isFinishing()) { return false; } } return true;}
参考:
https://blog.csdn.net/wjj1996825/article/details/80280109
https://blog.csdn.net/a940659387/article/details/50555327
更多相关文章
- Android加载Gif动画实现代码
- android 根据SD卡中图片路径读取并显示SD中的图片――源代码
- Android中多层Fragment嵌套,调用相册返回Uri无法显示图片的问题解
- Android WebView图片显示问题
- android 缩放图片与内存溢出
- android image cache 图片缓存 异步 下载
- android studio中.9.png图片处理
- 【Android开发小记--9】触摸事件---实现双指缩放图片
- android上传图片(同步上传)