【问题标题】:What is my context and where do I find it? [duplicate]我的背景是什么,我在哪里可以找到它? [复制]
【发布时间】: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


【解决方案1】:

在构造函数中使用this.mContext = context;,这样它就会将你的上下文传递给当前类的上下文。

并在您使用此类的地方传递getApplicationContextyourActivityName.this

如果您在片段中使用它,请使用getActivitygetContext

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2015-09-02
    • 2017-01-08
    • 2021-06-12
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多