Stack Overflow archive
0 score

get the context from an non-activity class into a non-activity

score
0
question views
898
license
CC BY-SA 3.0

You should pass the context to the constructor or method you are calling.

java
private Context mContext;

public RandomData(Context context) {
    mContext = context;
}

Edit:

Just for fun, you can actually get the application context in a static way. This is not recommended:

java
public static Context getContext() {
        Context context = null;
        try {
            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
            Method method = activityThreadClass.getMethod("currentApplication");
            context = (Application) method.invoke(null, (Object[]) null);
        } catch (Exception ignored) {
        }
        return context;
}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.