Android: how to get the file name and resource extension by resource ID

I have the following:

getResources().getResourceEntryName(resourceId); 

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

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

 getResources().getResourceEntryName(resourceId); 

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

+4
source share
4 answers

To get "res / drawable / pic.jpg", you can 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

+9
source

You can do it

  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]); } 
+2
source

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"

+2
source

Short answer: you cannot.

Another way to do this is to place your graphics in a resource folder. You can then access the files directly, without your application requiring permission.

You can, for example, do this in your activity:

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

I hope this accomplishes what you had in mind.


UPDATE : It seems like it is really possible, see Aleksandar Stojiljkovic answer .

+1
source

Source: https://habr.com/ru/post/1397896/


All Articles