get Context in non-Activity class

Developer picture Developer · Jul 29, 2013 · Viewed 140.6k times · Source

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?

Answer

Suji picture Suji · Jul 29, 2013

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);