2

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?

Micer
  • 8,731
  • 3
  • 79
  • 73
Miguel Ribeiro
  • 8,057
  • 20
  • 51
  • 74
  • 5
    Is "act" null or is "act.getResources()" null? – Juhani Nov 07 '10 at 14:03
  • Hey mate! You just gave the critical hint! I didn't check what was null and turns out it was "act". I'm working with a singleton when put the line in the wrong place! Thanks ;) – Miguel Ribeiro Nov 07 '10 at 14:09

2 Answers2

1

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

Miguel Ribeiro
  • 8,057
  • 20
  • 51
  • 74
0

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.

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
  • the class is a singleton (so it selfs instanciates) and it does not extends the class Activity to get access to getApplication() or getApplicationContext() – Miguel Ribeiro Nov 08 '10 at 23:48
  • Well a class doesn't have to extend Activity in order to obtain the correct context (even if it would and call getApplication() it would get the wrong context most-likely as you want to display stuff and get a hold of stuff in the main activity most of the times). But apparently you've solved your problem anyway so alls good. – Octavian Helm Nov 09 '10 at 08:53