Sungpah Lee
Sungpah Lee

Reputation: 1021

How to call resources with string name in android?

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.

Upvotes: 2

Views: 1156

Answers (2)

dahec
dahec

Reputation: 466

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);

Upvotes: 6

Devendra B. Singh
Devendra B. Singh

Reputation: 304

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.

Upvotes: 0

Related Questions