Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get Context in non-Activity class [duplicate]

People also ask

How do you find the context of a non activity class?

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? pass the context of ur current activity to the java class constructor... If your non-activity class is a Fragment , see stackoverflow.com/questions/8215308/using-context-in-a-fragment.

Can context be cast to activity?

The Best Answer is getApplicationContext(); Wherever you are passing it pass this or ActivityName. this instead. you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity .

How do you find the context of an activity class?

From B activity you create a object of class A using this constructor and passing getApplicationContext(). Show activity on this post. If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested.


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