Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing contents of res/raw programmatically (Android)

Tags:

java

android

I'm working on an app for Android with a few other people, and the primary content is specified by our designers as text files in a certain file format, which we then parse, process, and serve in the app. We're currently storing them in res/raw.

This makes things great for the designers because when they want to add content, they simply add a file to res/raw. This is annoying as a developer, however, since we developers then need to add R.raw.the_new_file to an array in the code specifying which files to process at startup.

Is there a way to access the resource ID's of res/raw programatically? Ideally when the application starts, we could make a call to see which files are in res/raw, process all of them, so we could eliminate the small overhead with matching up the contents of res/raw with that of our array in the code.

The most promising path I've seen is getAssets from Resources, which would let me call list(String) on the AssetManager, but I've had trouble getting this to work, especially since you can't directly call "res/raw" as your filepath (or at least, it hasn't worked when I've tried.

like image 872
pablo.meier Avatar asked May 10 '10 14:05

pablo.meier


2 Answers

You could use reflection.


ArrayList<Integer> list = new ArrayList<Integer>();
Field[] fields = R.raw.class.getFields();
for(Field f : fields)
try {
        list.add(f.getInt(null));
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) { }

After that list holds all resource IDs in the res/raw folder. If you need the name of the resource... f.getName() returns it.

like image 114
Padde Avatar answered Oct 15 '22 00:10

Padde


This answer may be a bit late, you should use assets folder instead. There you can have a folder hierarchy and read it as a file system.

For your info the getAssets returns a manager for files in the "assets" folder of your Android project and not in "res/raw". "res/raw" goes into the "R" Java Package. assets.list(path) Returns an array of files in the given folder relative to your assets folder. The asset's folder is also not a traditional folder, but Android abstracts it so it "feels" like regular files. This becomes more important if you are doing JNI and want to read your assets from c/c++.

like image 41
over_optimistic Avatar answered Oct 14 '22 23:10

over_optimistic