Get application context from non activity singleton class

前端 未结 3 1957
日久生厌
日久生厌 2020-11-27 18:14

In my android project, I have ImageAdapter class in which I pass app context for some further needs.

public class ImageAdapter extends BaseAdapter {
    priv         


        
3条回答
  •  天涯浪人
    2020-11-27 18:38

    APPROACH #1:

    Since you specify that ImageAdapter is a singleton, one simple answer is to create that singleton from a class that has access to app context:

    public class MyApplication extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            ImageAdapter.createIt(this);
        }
    }
    
    public class ImageAdapter extends BaseAdapter {
        private static ImageAdapter it;
        // Get the singleton.
        public static ImageAdapter getIt() {
            return it;
        }
        // Call this once, to create the singleton.
        public static void createIt(Context context) {
            it = new ImageAdapter(context);
        }
    
        private final Context c;
        private ImageAdapter(Context context) {
            c = context;
        }
    }
    

    APPROACH #2:

    If it were not a singleton, then I would use the accepted answer. In that case, remove the local variable from ImageAdapter, because context can always be obtained from MyApplication. Expanding on the accepted answer, if you want a local method as a convenience, define ImageAdapter.getContext(). Complete solution:

    public class MyApplication extends Application {
        private static Context appContext;
        public static Context getContext() {
            return appContext;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            appContext = this;
        }
    }
    
    public class ImageAdapter extends BaseAdapter {
        public ImageAdapter() {
        }
    
        // [Optional] Call this whenever you want the app context.
        private Context getContext() {
            return MyApplication.getContext();
        }
    }
    

提交回复
热议问题