I am working on a mobile library app. I have a 3-4 db files of books stored in raw folder. If I know the name of the book then I first copy this file to /databases/book_name.db and then access them as required. I use
InputStream fileInputStrea开发者_Python百科m = getResources().openRawResource(R.raw.book_name);
for accessing these files.
Now, I want to pass the book name and then dynamically generate the resource identifier R.raw.book_name using the string book_name. Is there a way by which I can generate this identifier?
Use Resources.getIdentifier() method:
int resId = getResources().getIdentifier("raw/book_name", null, this.getPackageName());
If your code not in activity or application, you need to get Context first.
Context context = getContext(); // or getBaseContext(), or getApplicationContext()
int resId = context.getResources().getIdentifier("raw/book_name", null, context.getPackageName());
You can use the answer I gave here: Android: Accessing string.xml using variable name
Try:
int identifier = getResources().getIdentifier(bookname, "raw", "<application package class>");
EDIT: meh, its raw.
Based off of Sergey's answer.
I'm using this in a CursorAdapter to DRY up the code and the final version that worked was:
String attribute = "company_name";
String packageName = view.getContext().getPackageName();
int resourceId = view.getResources().getIdentifier(attribute, null, packageName);
Actually, this was causing me problems so I switched to the following, which seemed more stable:
int resourceId = R.id.class.getField(attribute).getInt(null);
精彩评论