After trying to figuring this out by myself for quite some time, it's time to ask you: the community! I'm sure the solution should be around somewhere in another post, but I simply cannot find it (or apply it to my code).
I want to achieve the following: When launching my android application, I want to call a method which does the following:
Read all filenames in the "res/raw" directory, in which I have stored several jpegs, and store the names of these files to an array.
I suppose it shouldn't be too difficult to answer, but I simply cannot figure it out by myself. I've looked into the listFiles() command, and I suppose that is the way to go, but I cannot get it working. Here you will find a piece of my code with the relevant lines:
public class Example{
File[] imageNames;
public void onCreate(){
scanFolder();
useTheDataFromScanFolder();
}
public void scanFolder (){
int numberOfFiles = new File("res\raw").listFiles().length;
imageNames = new File("res\raw").listFiles();
}
useTheDataFromScanFolder(){
//here I want to use numberOfFiles and the array imageId
}
}
I hope you can either solve my issue, or push me into the right direction! Thanks in advance!!
EDIT: Thanks to CommonsWare I managed to solve my issue, I managed to get it working with the following code (the pictures are now stored in /assets/resources/):
String [] fileList;
public void onCreate(Bundle savedInstanceState) {
listAssetFiles("resources");
}
public boolean listAssetFiles(String path) {
try {
fileList = getAssets().list(path);
} catch (IOException e) {
return false;
}
return true;
}
Read all filenames in the "res/raw" directory
There is no res/raw/
directory on the Android device. There may be a res/raw/
directory in your Android app project on your development machine. Resources are not files on the device, but instead are entries in the APK file. And, hence, there are no filenames.
The simpler solution would be to move these things to assets/
. Then you can use AssetManager
and list()
to retrieve the names of those assets, and use open()
to get an InputStream
on one. While assets are not files on the device either, the AssetManager
API is more file-like.
If you want to stick to raw resources, you would need to use Java reflection to iterate over all static
fields defined on R.raw
to find their resource IDs, then use openRawResource()
on a Resources()
object to get the InputStream
.