Issue
I am 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 it 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 says:
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 tried to search inside the AppCompatActivity class (because my original activity extend it) but I can't find.
So my doubts are:
The main problem is: how can I correctly use the BitmapFactory.decodeResource() method inside my previous ImgUtility clas?
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 it declared?
Solution
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:
java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity
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.
Answered By - Eric B.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.