【发布时间】:2019-10-17 22:50:28
【问题描述】:
我之前问过类似的问题,但我不明白该怎么做,我还阅读了其他解决方案,例如:What is a NullPointerException, and how do I fix it? 我还是不知道怎么办,请帮忙:
据我了解是我的context = null; 和我不知道为什么,以及如何解决它......
我编写了一个 UniversImageLoader.class 以便能够在多个活动中加载图像。现在我已经在我的所有活动中启动了它,但是在我的 UIL 类中,我需要传递一个上下文。
public class UniversalImageLoader {
private static final int defaultImage = R.drawable.ic_android;
private Context mContext;
public UniversalImageLoader(Context context) {
mContext = context;
}
public ImageLoaderConfiguration getConfig(){
//File cacheDir = StorageUtils.getCacheDirectory(mContext);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext)//<--the error is in this line
.memoryCacheExtraOptions(480, 800) // default = device screen dimensions
.diskCacheExtraOptions(480, 800, null)
.threadPriority(Thread.NORM_PRIORITY - 2) // default
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.memoryCacheSizePercentage(13) // default
.diskCacheSize(50 * 1024 * 1024)
.diskCacheFileCount(100)
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
.imageDownloader(new BaseImageDownloader(mContext)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.writeDebugLogs()
.build();
return config;
}
在 HomeActivity 中:[在每个 Activity 中我都这样称呼它]
private void initImageLoader(){
UniversalImageLoader universalImageLoader = new UniversalImageLoader(mContext);
ImageLoader.getInstance().init(universalImageLoader.getConfig());
}
在所有这些活动中,我在 OnCreate 方法中这样称呼它:
initImageLoader();
所以我已经阅读,查看了其他解决方案,但找不到可以理解的答案...您的指导将不胜感激!
【问题讨论】:
-
只需在您的活动中将其作为参数而不是 mContext 传递。新的 UniversalImageLoader(this);
-
一个错误:UniversalImageLoader中的UniversalImageLoader(android.content.Context)不能应用到activity
-
好的。如果你在片段中,那么你需要传递 requireContext() 。新的 UniversalImageLoader(requireContext())
-
考虑到它会在多个活动中使用这一事实,他使用 getApplicationContext() 并将类转换为单例不是更好(在这个特定的上下文中)吗?跨度>
-
@darius f...非常感谢我所需要的...
标签: java android universal-image-loader