Why do I get this “Context = NullPointerException” error in my homework? [duplicate]

本小妞迷上赌 提交于 2019-12-02 13:29:38

When you are creating object of UniversalImageLoader class, pass getApplicationContext() instead of activity context.

Application context is available through out application while activity context is bound to activity life cycle.

Update:

Application Context: It is an instance which is the singleton and can be accessed in an activity via getApplicationContext(). This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of an activity

private void initImageLoader(){
    UniversalImageLoader universalImageLoader = new UniversalImageLoader(getApplicationContext());
    ImageLoader.getInstance().init(universalImageLoader.getConfig());
}

Activity Context This context is available in an activity. This context is tied to the lifecycle of an activity.

Here read more about the difference in Activity context and application context. https://blog.mindorks.com/understanding-context-in-android-application-330913e32514

For Multiple Activities you can initialize in Application class onCreate method.

public class MyApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
        // Initialize the Universal Image Loader here

    DisplayImageOptions defaultOptions = new 
    DisplayImageOptions.Builder()
            .cacheOnDisk(true).cacheInMemory(true).build();

    ImageLoaderConfiguration config = new 
    ImageLoaderConfiguration.Builder(getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions).build();

    ImageLoader.getInstance().init(config);


}

Then in your Activity get image Loader instance like this.

ImageLoader mImageLoader = ImageLoader.getInstance();

Also you need to add your Application class in AndroidManifest like this.

<application
    android:name=".MyApplication"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!