2

I'm now trying to call the resources( in my application they are mp3 files and images). For the mp3 file part, my code goes like this ( not working obviously!)

if(i==1)
{
hoho= MediaPlayer.create(getApplicationContext(), R.raw.univ_day1);
hoho.start();
}
else if (i==2)
{
hoho= MediaPlayer.create(getApplicationContext(), R.raw.univ_day2);
hoho.start();  
}

...

In my application, there are hundreds of mp3 file inside the application. So what I want to do is briefly summarize code into something like this.

hoho=MediaPlayer.crate(getApplicationContet(), R.raw.univ_day+"i"); //This also looks really awkward.

If I knew how to write down code just like above one. How can I handle the name of raw files and the form like "R.raw...."? If I can do, then I also can apply similar approach to the image resources.

Jongware
  • 22,200
  • 8
  • 54
  • 100
Sungpah Lee
  • 1,003
  • 1
  • 13
  • 31
  • put your audio files in the assets directory and setup arrays of strings/filename then traverse it `AssetFileDescriptor descriptor = contex.getAssets() .openFd(fileName + i);` `mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());` `descriptor.close()` – Spurdow Aug 09 '14 at 14:43
  • possible duplicate of [Android: How do I get string from resources using its name?](http://stackoverflow.com/questions/7493287/android-how-do-i-get-string-from-resources-using-its-name) – nhaarman Aug 09 '14 at 14:43
  • No its not. Here question is about getting the list of media files from the res folder not the list all the string resources names. – Devendra B. Singh Aug 09 '14 at 15:06

2 Answers2

6

You can get resource id by its name using public int getIdentifier (String name, String defType, String defPackage) method. For example:

int id = getResources().getIdentifier("univ_day"+i, "raw", getPackageName());
hoho = MediaPlayer.create(getApplicationContext(), id);
dahec
  • 466
  • 5
  • 10
0

We can list all the names of raw assets, which are basically the filenames without the extensions, we can do this as -

public void listRaw(){
    Field[] fields=R.raw.class.getFields();
    for(int count=0; count < fields.length; count++){
        Log.i("Raw Asset: ", fields[count].getName());
    }
}

Next you'll need to refer to them by the integer assigned to that resource name. You can get this integer as:

int resourceID=fields[count].getInt(fields[count]);

This is the same int which you'd get by referring to R.raw.yourRawFileName.

In your code you can use this like -

hoho= MediaPlayer.create(getApplicationContext(), resourceID);
hoho.start();

Next you can apply JAVA logic to play previous current and next media files. Please let know if you need help here also.