Search code examples
javaandroidgradleandroid-productflavorsfile-structure

Do I need to separate java files for different version of app when using product flavors?


First time using product flavors and I'm not sure if I need to put an exact duplicate of everything in each product folder eg. src/flavor1/com/app/pro/company/ "all my java files". I have the same file structure for free version. I try this and I get the "Duplicate class found in the file "C:\blah\blah\Settings.java" error. I setup a bool in the gradle to use for the separating free vs. paid version in the file mentioned. Any advice from here? Is there anyway to use one java file for both versions?

I'm using buildConfigField("boolean", "demomode", "false") in the gradle.

Thanks in advance!


Solution

  • If a Java file is shared between all flavors in a flavor dimension, then you can keep a single copy in your main source set. This reduces duplication!

    If any flavor in a flavor dimension requires a customized version of a specific Java file, then you must remove the copy of that same Java file from your main source set, and place appropriately customized versions in every flavor-specific source set for that flavor dimension. You can't have flavor specific copies of the Java file "override" the main copy.

    Based on your specific error, it sounds like either

    1. paid and free are not part of the same flavor dimension, or
    2. you still have a copy of your Java files in your main source set (usually located in src/main).

    If case 1, make sure both flavors are part of the same dimension.

    If case 2, delete the copies of any files that are customized per-flavor from the main source set, and delete the copies of any files that are shared between flavors from the flavor-specific source sets (leaving them in the shared source set main). This may then allow you to avoid defining the BuildConfig boolean and leverage the fact that you have flavor-specific classes to implement the differences between free and paid modes.

    See the docs for more background on source sets.