Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically generate the raw resource identifier in android?

Tags:

android

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?

like image 670
cooltechnomax Avatar asked Jun 03 '11 03:06

cooltechnomax


People also ask

What is r raw in Android?

The raw (res/raw) folder is one of the most important folders and it plays a very important role during the development of android projects in android studio. The raw folder in Android is used to keep mp3, mp4, sfb files, etc. The raw folder is created inside the res folder: main/res/raw.

What is Android resource directory?

The res/values folder is used to store the values for the resources that are used in many Android projects to include features of color, styles, dimensions etc.


1 Answers

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());
like image 99
Sergey Glotov Avatar answered Sep 20 '22 02:09

Sergey Glotov