Reputation: 16988
I have a file in the res/raw folder called "book1tabs.txt", but in general I will not know what it is called. Then I have to do something like follows:
InputStream in = this.mCtx.getResources().openRawResource(R.raw.book1tabs);
But I want to use a string variable, like
String param = "book1tabs";
And be able to open up that same input stream.
Is there any way to do this?
Thanks
Upvotes: 3
Views: 3433
Reputation: 42016
You can do something like this
String param = "book1tabs";
InputStream in = this.mCtx.getResources().openRawResource(mCtx.getResources().getIdentifier(param,"raw", mCtx.getPackageName()));
getIdentifier()
will return the id from R.java
of particular parameter you passed.
Exactly what it will do is as follow
For more information http://developer.android.com/reference/android/content/res/Resources.html
Upvotes: 8
Reputation: 28349
I find this method to be very useful to pull all sorts of resources by their string names...
@SuppressWarnings("rawtypes")
public static int getResourceId(String name, Class resType){
try {
Class res = null;
if(resType == R.drawable.class)
res = R.drawable.class;
if(resType == R.id.class)
res = R.id.class;
if(resType == R.string.class)
res = R.string.class;
if(resType == R.raw.class)
res = R.raw.class;
Field field = res.getField(name);
int retId = field.getInt(null);
return retId;
}
catch (Exception e) {
// Log.d(TAG, "Failure to get drawable id.", e);
}
return 0;
}
This will return the numeric id (assuming such a resource exists). For the Class pass in R.drawable
and for the string whatever it's xml based ID name is.
I always have this method hanging around all my projects for easy access.
Upvotes: 2