135

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Developer
  • 1,803
  • 2
  • 15
  • 26
  • 1
    pass the context of ur current activity to the java class constructor... – user1969053 Jul 29 '13 at 07:11
  • 1
    If 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
  • 4
    If 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 Answers1

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