In an android Application, is there any way to get the context in android in a non-activity class if the activity class name is known?
Asked
Active
Viewed 1.7e+01k times
135
-
1pass the context of ur current activity to the java class constructor... – user1969053 Jul 29 '13 at 07:11
-
1If your non-activity class is a `Fragment`, see http://stackoverflow.com/questions/8215308/using-context-in-a-fragment. – dinosaur Apr 13 '16 at 09:35
-
4If you want to avoid context passing, then make a class that extends Application class, and inside that define- private static Context appContext; and at onCreate(){ this.appContext =getApplicationContext() ;}, and make public static Context getContext(){ return appContext ;} method that will return the application context and use in onActivity class. – B.shruti Jan 31 '18 at 06:13
1 Answers
190
If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:
class YourNonActivityClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourNonActivityClass(Context context){
this.context=context;
}
}
You can create instance of this class from the activity as follows:
new YourNonActivityClass(this);

Suji
- 6,044
- 2
- 19
- 17
-
13What if I have a static instance of my class, there I have a problem with static contexts. What should I do ' – Jonathan Aste May 31 '17 at 19:10
-
5
-
1