Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android reading from local.properties

I have local.properties file in root of my project.

sdk.dir=C\:\\Users\\vucet\\AppData\\Local\\Android\\Sdk
versionName='7.0'

and in build gradle in app module I am trying to get versionName on this way

Properties properties = new Properties()
if (project.rootProject.file('local.properties').exists()) {
    properties.load(project.rootProject.file('local.properties').newDataInputStream())
}

def getVerCode = { ->
    def code = project.hasProperty("versionCode") ? project.versionCode.toInteger() : 1000
    return code
}

def getVerName = { ->
    def name = project.hasProperty("versionName") ? project.versionName.toString() : "5.0"
    return name
}

but every time I get 5.0 value. Please can anyone help me ?

like image 680
eJoe Avatar asked May 11 '17 16:05

eJoe


2 Answers

Reading local.properties using gradle and use them in your Android app java code.

local.properties:

TOKEN="yyyyy" SERVER_URL="https://foo.com"

build.gradle:

Properties properties = new Properties()
if (project.rootProject.file('local.properties').canRead()) {
        properties.load(project.rootProject.file("local.properties").newDataInputStream())
}

buildConfigField 'String', 'TOKEN', properties.getProperty('TOKEN', '"xxx"')
buildConfigField 'String', 'SERVER_URL', properties.getProperty('SERVER_URL', '"https://example.com/"')

Android java code

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    Log.d("TAG", "My 'token' is: " + BuildConfig.TOKEN);
    Log.d("TAG", "My 'server url' is: " + BuildConfig.SERVER_URL);

}

like image 85
giltsl Avatar answered Nov 14 '22 23:11

giltsl


Hi I find way how to read local.properties file in gradle script

def Properties properties = new Properties()

if (project.rootProject.file('local.properties').canRead()) {
    properties.load(new FileInputStream(project.rootProject.file('local.properties')))
    def versionBuild = properties['versionName'].toString()

} else {
    throw new GradleException("Could not read version.properties!")
}

def getVerCode = { ->
    def code = properties.getProperty("versionCode", "1").toInteger()
    return code
}

def getVerName = { ->
    def name = properties.getProperty("versionName", "1")
    return name
}
like image 33
eJoe Avatar answered Nov 14 '22 22:11

eJoe