About Application to get context, getApplicationContext method Null pointer problem.

2553 단어
The application gets the context, and the premise must be initialized in the oncreate method in the application.

solve:


public class AppUtils {

    private static Application application;

    public static void setApplication(Application application) {
        if (AppUtils.application != null) {
            throw new IllegalStateException("application already holded 'application'.");
        }
        AppUtils.application = application;
    }
    public static Context getContext() {
        return application.getApplicationContext();
    }
}



Initialize in applicaition class

@Override
public void onCreate() {
    super.onCreate();
    // Context
    AppUtils.setApplication(this);
    Fresco.initialize(this);
    initPackageName();
}


Do this by

Context context = AppUtils.getContext();

좋은 웹페이지 즐겨찾기