Reputation: 2676
In an Android application, I am trying to get a list of files that are in res/drawable-hdpi
My understanding is that I should be able to get the unique identifier for a subfolder of res
, and then iterate through the fields of R
to filter files that aren't within a range of the folder's ID.
int directoryId = getResources().getIdentifier("drawable-hdpi", "drawable", getPackageName());
Field[] fields = R.drawable.class.getFields();
for (Field field : fields) {
int resourceId = field.getInt(null);
if (resourceId >= directoryId && resourceId < (directoryId + 100)) {
// resourceId is a file in the drawable-hdpi directory
}
}
However, the directoryId
is set to 0
. I understand that this is the expected behavior if
However, none of these things is the case, so I'm really confused. Here's the folder structure
res
├── drawable
│ ├── ic_launcher_background.xml
│ ├── ic_launcher_foreground.xml
│ └── ic_wallpaper_black_24dp.xml
├── drawable-hdpi
│ ├── img1.jpg
│ ├── img2.jpg
│ └── img3.jpg
...
It's the img1.jpg
, img2.jpg
, and img3.jpg
, that I'm interested in. I can see them in the list of fields of R
, so the folder must be being included. I've triple checked that the folder meets the naming requirements.
What am I doing wrong?
Upvotes: 1
Views: 142
Reputation: 1006859
I am trying to get a list of files that are in res/drawable-hdpi
That is not possible at runtime. You could create a Gradle task or other compile-time script that examines your hard drive and generates something that contains this information (Java code using JavaPoet, JSON file as an asset, etc.). Or, instead of using res/
, you could put your images in assets/
, then use getAssets().list()
on a Context
to iterate over the assets (warning: libraries may also package assets, so don't assume they are all yours).
My understanding is that I should be able to get the unique identifier for a subfolder of res, and then iterate through the fields of R to filter files that aren't within a range of the folder's ID.
There are some problems with this:
Resource directories do not have IDs
From your standpoint, resource IDs are random numbers that can change from build to build
R
represents all resources in a unified identifier space, not ones tied to some particular set of resource qualifiers (e.g., your strings, drawables, layouts, dimensions, and so on all get R
values, in semi-arbitrary order).
I understand that this is the expected behavior
It is the expected behavior all the time. I do not know where you saw otherwise.
Upvotes: 2