Question

I'm defining a class that sets a Drawable attribute in an object. The problem is that I can't access the getResource().getDrawable(int resourceId) method unless I have some Context. What I did was to send to that class an activity instance (let's call it "act") and then I did:

act.getResources().getDrawable(R.drawable.whellchair)

but, when executing that line it throws a NullPointerException.

When idea how to accomplish this?

Was it helpful?

Solution

I found the problem! I'm using a singleton and I put the line accessing the "act" in a static method... how fool of me ...

Sorry and thank you Juhani for the comment :)

OTHER TIPS

Pass that the application context to the constructor of your class. In the main application class you just get the context by invoking the getApplication() method if you need the a lifetime aware context or getApplicationContext() if you need a the context which is tied to the current process.

Example:

private Context ctx = getApplication();

... some code ...

MyClass myClass = new MyClass(ctx);

Your classes' constructor of course has to handle the context accordingly (i.e. setting a private member of type Context to the passed value) like this.

private Context ctx = null;

public MyClass(ctx) {
    this.ctx = ctx;
}

Then you can use the context for whatever you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top