Question

i was searching for a solution how to reference a .mp3 file in my raw folder via a String.

Exactly I want to loop through the raw files which are all named player1.mp3, player2.mp3 and so on and store the resource id in an int array, which should contain the ids in the right player order.

My thought was using something like this:

int[] playerArray = new int[100];
String filename;
for(int i = 0; i<100; i++){
   filename = "player"+String.valueOf(i);
   playerArray = R.raw.filename; //I know, this does not work
}

Can anyone tell me an easy way to save the fileids in the right order in an array, and if there is no file with playerX.mp3 just write a 200 in playerArray[X]

Thanks in forward ;)

Was it helpful?

Solution

You can maybe use this code:

int rawId = context.getResources().getIdentifier(filename, "raw", context.getPackageName());

With the method getResources() you can get the id of all the ressource. The second paramter is the type of the ressource (string, drawable, raw, ...)

Your code will be something like that:

int[] playerArray = new int[100];
String filename;
for(int i = 0; i<100; i++){
   filename = "player"+String.valueOf(i);
   int rawId = context.getResources().getIdentifier(filename, "raw", context.getPackageName());
   playerArray[i] = rawId;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top