How to access build config fields from lib project in Android

I created a lib project with build config configuration. I have published this to Maven and now I am able to consume this lib in another app. Now I am converting this new app to lib and using this lib in another new app.

Here I am facing a issue. I am not able to access the build config on my root lib. I am getting NoSuchFieldException. But when I try with dubug build it is working as expected. When I try with release build only I am getting exception.

I will explain more about this.

Project 1 - root lib project

Project 2 - new lib project consuming Project 1

Project 3 - New app consuming Project 2

enter image description here

When I use Project 2 as debug build in project 3 it is working as expected. When I use Project 2 as release build in project 3 I am getting NoSuchFieldException.

To get the value from build config I am using the following code in Project 1.

public static String getBuildConfigValue(Context context, String fieldName) {
        try {
            Class<?> clazz = Class.forName(context.getPackageName() + ".BuildConfig");
            Field field = clazz.getDeclaredField(fieldName);

            return Objects.requireNonNull(field.get(null)).toString();
        } catch (ClassNotFoundException e) {

            Log.e("ClassNotFoundException in getBuildConfigValue ",e);
        } catch (NoSuchFieldException e) {

            Log.e("NoSuchFieldException in getBuildConfigValue ",e);
        } catch (IllegalAccessException e) {
            Log.e("IllegalAccessException in getBuildConfigValue ",e);
        }
        return null;
    }

How can I resolve this issue?

Upvotes: 0

Views: 40

Answers (1)

Need to expose the build config file in the second project. This solved my issue. Added the following code in app progaurd.

-keep public class com.mobile.basesdk.BuildConfig{
*;
}

Upvotes: 0

Related Questions