Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access drawable from non activity class

I am in a situation where I have to use the drawable folder of my app form a non activity class. I tried using the parent activity with the following code:

ParentActivity pa = new ParentActivity();
Drawable d = pa.getResources()..getDrawable(R.drawable.icon);`

But this returns me a NulLPointerException. How can I achieve this?

like image 478
Andro Selva Avatar asked Jun 02 '11 12:06

Andro Selva


1 Answers

Pass the context object as a parameter to the constructor of the non Activity class.

Then use that context object to get the Resources.

Example

public class MyClass {
  Context context;
  public MyClass(Context context) {
      this.context = context;
  }

  public void urMethod() {
    Drawable drawable=context.getResources().getDrawable(R.drawable.icon);
    // use this drawable as u need
  }
}
like image 121
Balaji.K Avatar answered Nov 02 '22 23:11

Balaji.K