'Can't programmatically get resource from another module

I have an android project with several gradle modules. Dependencies beetween modules look like this:
app <-- coremodule <-- featuremodule

There are a resources in coremodule (strings and colors).

When I use them in layout from featuremodule everything is OK, they are avaliable and work as expected. But when I try to get them programmaticully in Activity from featuremodule I get an exception: Unresolved reference: R

So android:text="@string/res_from_core_module" works and myTextView.setText(R.string.res_from_core_module) doesn't work.

Have anyone ideas why it happens and how to solve this?



Solution 1:[1]

The reason for such behavior was adding 'coremodule' dependency with compileOnly.

build.gradle for app module looked like:

dependencies {
    ...
    compileOnly project(path: ':coremodule')
    ...
}

if change compileOnly with implementation (or api) everything is OK

dependencies {
    ...
    implementation project(path: ':coremodule')
    ...
}

Solution 2:[2]

I think the R points to the Resources of your app. Check the imports at the beginning of the file.

You should explicitly point the Resource folder in the method like this:

myTextView.setText(com.coremodule.R.string.res_from_core_module)

Solution 3:[3]

Add this to all modules to share resources, classes, functions

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])

    ...
}

Solution 4:[4]

Latest answer !!! It will make everything accessible to your app module.

dependencies {
    ...
    api project(': coremodule')
    ...
}

Solution 5:[5]

Please use like this:

myTextView.setText(getString(R.string.res_from_core_module));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mikhail Sidorov
Solution 2 BEAGLE ENTERTAIN
Solution 3 hungtran273
Solution 4 Shahbaz Hashmi
Solution 5 Raman Sharma