14

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 fileInputStream = 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?

cooltechnomax
  • 681
  • 3
  • 10
  • 21

3 Answers3

24

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());
Inverce
  • 1,487
  • 13
  • 27
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
  • 11
    Just a hint, if you have a file with extension, for example: `raw/list_users.json` then do not include extension `.json`, simple: `getResources().getIdentifier("list_users", "raw", "")` do a trick. – divix Feb 28 '16 at 14:22
5

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.

Community
  • 1
  • 1
Femi
  • 64,273
  • 8
  • 118
  • 148
1

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);
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245