AndreaNobili AndreaNobili - 1 year ago 195
Android Question

Why I can't use the BitmapFactory.decodeResource() metod into an utility class (a class that is not an activity)?Cannot resolve method getResources()

I am absolutly new in Android development and I am finding some problem using the BitmapFactory.decodeResource() method into an utility class (a class that is not an activity class).

So I am doing some refactoring on my code and I have to move this code line:

Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chef_hat_ok);

from an activity class method to a method that i declared inside an utility class.

It worked fine into the activity class but moving int into the utility class method, something like this:

public class ImgUtility {

public Bitmap createRankingImg(int difficulty) {

// Create a Bitmap image starting from the star.png into the "/res/drawable/" directory:
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chef_hat_ok);

return myBitmap;



I obtain an IDE error message on the getResources() method, the IDE say to me:

Cannot resolve method 'getResources()'

I think that it happens because the getResources() method retrieve something that is related to an activity class.

Looking into the old code I can see that the getResources() method return a ContextThemeWrapper object. I tryied to search inside the AppCompatActivity class (because my original activity extend it) but I can't find.

So my doubts are:

1) The main problem is: how can I correctly use the BitmapFactory.decodeResource() method inside my previus ImgUtility clas?

2) Why when I use the BitmapFactory.decodeResource() method it take the ContextThemeWrapper object (returned by the getResources() method) as parameter? What exactly represent this object? Is it related to an activity class or what? Where is declared?


Answer Source

getResources() method is available in Context. You can simply do this in your Utility class:

public class ImgUtility {

    public Bitmap createRankingImg(Context context, int difficulty) {

        // Create a Bitmap image starting from the star.png into the "/res/drawable/" directory:
        Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.chef_hat_ok);
        return myBitmap;



To answer your second question, see this:

   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.view.ContextThemeWrapper

The getResources() method is actually present in the Context class. All the inhereting classes also have the getResources() method. Hence, when you call getResources() from your Activity(which is a sub class of Context), it easily gets called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download