Search code examples
androidandroid-resourcesandroid-productflavors

Reference resource id from resource


I have a project with multiple flavors, apple and banana. It references a file that is stored in the raw resource directory. I would prefer to avoid naming each one database.sqlite and instead keep the name relevant to the flavor, apple.sqlite and banana.sqlite. In my code, I have a line that reads as

getResources().openRawResource(R.raw.apple);

Is it possible to create an integer resource that could essentially link to the right id, or would I be better off making a class in each flavor that would have the link to it?


Solution

  • You can create dedicated source sets for build types, product flavors (such as apple and banana), and build variants. You can create resource aliases, to give a resource another identifier. You should be able to mash these up to get what you want.

    I assume, from your question, that you have apple/res/raw/apple.sqlite and banana/res/raw/banana.sqlite in your project. If so, then:

    • Create apple/res/values/ids.xml, and in there have <item type="raw" name="whatever">@raw/apple</item>

    • Create banana/res/values/ids.xml, and in there have <item type="raw" name="whatever">@raw/banana</item>

    • Use R.raw.whatever to identify this resource in your code in main

    (where you can replace whatever with, like, whatever)

    Here, you are setting up a common alias (whatever) for the resource, pointing the flavor-specific definition of the alias to the flavor-specific resource.