zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

【错误记录】Android Gradle 配置报错 ( gradle.properties 配置到 BuildConfig 中需要注意类型转换 | 位置: 类 BuildConfig )

Android错误配置gradle 报错 记录 需要 位置
2023-09-14 09:07:28 时间





一、报错信息



报错信息 :

D:\002_Project\002_Android_Learn\ClassLoader_Demo\app\build\generated\source\buildConfig\debug\com\example\classloader_demo\BuildConfig.java:15: 错误: 找不到符号
  public static final String market = GooglePlay;
                                      ^
  符号:   变量 GooglePlay
  位置: 类 BuildConfig

在这里插入图片描述

在 Android Studio 项目根目录的 gradle.properties 配置文件中 , 配置

# 配置是否在 Google Play 上架
isGooglePlay=true
# 配置当前的应用市场
market=GooglePlay

在这里插入图片描述

在 build.gradle 中的对应配置如下 :

android {

    defaultConfig {
        // 应用是否在 Google Play 上架
        buildConfigField("boolean", "isGooglePlay", isGooglePlay)
        // 当前的应用市场
        buildConfigField("String", "market", market)
    }
}

生成的 BuildConfig.java 配置如下 :

/**
 * Automatically generated file. DO NOT MODIFY
 */
package com.example.classloader_demo;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.example.classloader_demo";
  public static final String BUILD_TYPE = "debug";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";
  // Field from default config.
  public static final boolean isGooglePlay = true;
  // Field from default config.
  public static final String market = GooglePlay;
}

最后的 GooglePlay 字符串没有双引号导致错误 ;





二、解决方案



使用

buildConfigField("String", "market", "\"${market}\"")

Groovy 代码 , 可以生成 BuildConfig.java 中的如下配置 :

public static final String market = "GooglePlay";

字符串的双引号需要自己使用转义字符添加上去 , 否则无效 ;

"\"${market}\"" 的 第一层双引号 , 是因为 buildConfigField 函数需要传入三个字符串类型的变量 , 第三个参数必须是字符串 ;

第二层双引号 \" \" 使用转移字符 , 这才是在 BuildConfig 中显示的双引号 , 内部的 ${market} 就是 GooglePlay 配置内容 ;