providence
providence

Reputation: 29463

Access Application Context from class that doesn't extend Activity/Service

I handle login for my application in a class that extends application. The application then maintains an object of this class at all times. This means that I can access that specific object from any class that extends activity or service by calling

LoginModeller lm = ((LoginModeller)getApplicationContext());

However, I now need to access the object from a class that does not extend activity or service (It extends nothing). Is there some way to access the application context from a class like this, or I do have to re-factor my LoginModeller as a singleton or something?

Upvotes: 2

Views: 2365

Answers (2)

Macarse
Macarse

Reputation: 93133

I don't know if you are using DI with roboguice but I am :)

From my point of view, the cleanest way to do this is using a staticInjection. Here's how.

Upvotes: 1

Matthew
Matthew

Reputation: 44919

Who creates this object? In your constructor you can pass in a Context and store it as an instance variable:

private final Context context;

public MyObject(Context context) {
    this.context = context;
    ...

Upvotes: 3

Related Questions