Home » Android » android – get Context in non-Activity class

android – get Context in non-Activity class

Posted by: admin March 11, 2020 Leave a comment

Questions:

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?

How to&Answers:

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