SARose
SARose

Reputation: 3725

Get Resource ID from Uri

Do you guys know if it is possible to get the resource id from a Uri?

For example from

Uri soundUri = Uri.parse("android.resource://" + packageName + "/raw/" + name);

get the equivalent of this

R.raw.name

Thanks guys!

Upvotes: 1

Views: 2303

Answers (2)

Hana Bzh
Hana Bzh

Reputation: 2260

imageView.setImageResource(context.getResources().
         getIdentifier(name, "raw", context.getPackageName()));

Also you can use this

public static int getResId(String variableName, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

which is faster than getIdentifier

Upvotes: 1

mach
mach

Reputation: 8395

If the question is if it is possible to get a resource id by its name given in coding then - yes.

getIdentifier( name , "raw" , packageName );

However thread lightly. It is using reflection and thus may easily break if you for example use proguard. You have been warned.

Upvotes: 1

Related Questions