Genry
Genry

Reputation: 1408

Android: How to retrieve file name and extension of a resource by resource ID

I have the following:

getResources().getResourceEntryName(resourceId);

The problem is, that it retrieves only the file name without the extension.

For example, if I have the following res/drawable/pic.jpg, the

getResources().getResourceEntryName(resourceId);

is returning the value "pic". The extension .jpg is missing.

Upvotes: 8

Views: 8724

Answers (4)

Kristian Bellò
Kristian Bellò

Reputation: 31

You can do so

    Field[] fields = R.raw.class.getFields();
    for (int count = 0; count < fields.length; count++) {

        // Use that if you just need the file name
        String filename = fields[count].getName();
        Log.i("filename", filename);
        int rawId = getResources().getIdentifier(filename, "raw", getPackageName());
        TypedValue value = new TypedValue();
        getResources().getValue(rawId, value, true);
        String[] s = value.string.toString().split("/");
        Log.i("filename", s[s.length - 1]);
    }

Upvotes: 3

devsnd
devsnd

Reputation: 7722

Short answer: You can't.

Another way to do this, would be to put your graphics inside the assets folder. Then you can access the Files directly, without your App needing any permission.

You can, for example, do so in your Activity:

AssetManager am = this.getApplicationContext().getAssets()
InputStream is = am.open(foldername+"/"+filename)
Bitmap myNewImage = BitmapFactory.decodeStream(is);

I hope that this will accomplish what you had in mind.


UPDATE: it seems it is indeed possible, see Aleksandar Stojiljkovic's answer instead.

Upvotes: 1

Timo Schuck
Timo Schuck

Reputation: 324

This should be the best solution:

 TypedValue value = new TypedValue();
    getResources().getValue(resourceId, value, true); 
String resname = value.string.toString().substring(13, value.string.toString().length());

resname = "pic.jpg"

Upvotes: 1

To get "res/drawable/pic.jpg" you could use this:

    TypedValue value = new TypedValue();
    getResources().getValue(resourceId, value, true);
    // check value.string if not null - it is not null for drawables...

    Log.d(TAG, "Resource filename:" + value.string.toString());
    // ^^ This would print res/drawable/pic.jpg

Source: android/frameworks/base/core/java/android/content/res/Resources.java

Upvotes: 21

Related Questions