-1

I am trying to call the following function to get the resource id:

Integer drawableId = Resources.getSystem().getIdentifier(newString, "drawable", getPackageName());

The issue here is that the id is always 0, as its not found/ invalid.

Is there a way to get call the getIdentifier() function from within a class and not in a activity or fragment?

Learn2Code
  • 1,974
  • 5
  • 24
  • 46
  • Try the following to access the application context. https://stackoverflow.com/a/5114361/13373270. Then use this context to access application resources where you need them. – codebod Jun 12 '21 at 21:13
  • @codebod: That is not a good idea for resources that are tied to the screen, such as layouts and drawables. The `Application` singleton does not know the details of the screen (e.g., density), in part because there may be more than one screen on the device. Use an `Activity` as the `Context` for resources like that, outside of very specialized scenarios. For the limited case of calling `getIdentifier()`, using the `Application` should be safe. – CommonsWare Jun 12 '21 at 21:29
  • Yes, the OP is trying to retrieve a resource identifier. – codebod Jun 12 '21 at 22:22

1 Answers1

0

Is there a way to get call the getIdentifier() function from within a class and not in a activity

No you can't; resource identifier values can vary from app launch to another; they are coupled to activities getResources()

But as long as you have something to see on the phone's screen, you must have an activity; no fragments without activity; and therefore you can pass it as method parameter to the class you want to call getIdentifier() on:

public class MyClass() {

    public static int getIdentifier(AppCompatActivity activity, String myDrawable) {
        return activity.getResources().getIdentifier(myDrawable, 
                                                     "drawable", activity.getPackageName());
    }

}
Zain
  • 37,492
  • 7
  • 60
  • 84