How to read value from gradle.properties in java module? - java

I have a project in Android Studio with a couple of modules.
The app module. With apply plugin: 'com.android.application'.
The androidLibrary module. With apply plugin: 'com.android.library'.
The javaLibrary module. With apply plugin: 'java'.
I want to declare some variables in the project gradle.properties file and be able to read them from the javaLibrary module.
I have declared the properties in the following ways according this documentation...
mysuperhost=superhost
systemProp.mysuperhost=superhost
ORG_GRADLE_PROJECT_mysuperhost=superhost
org.gradle.project.mysuperhost=superhost
... and tried to read them this way with no success:
System.getenv("mysuperhost");
System.getProperty("mysuperhost");
I know how to read properties from the BuildConfig class, but this is a generateed class in the app module (with apply plugin: 'com.android.application'), so this does not work for this particular case.

If you have some value inside of the your gradle.properties file like
mysuperhost=superhost
then write the following lines in the your build.gradle file (to grab property from gradle.properties file and add it into BuildConfig.java class):
// ...
// ...
android {
// Just for example
compileSdkVersion 23
// Just for example
buildToolsVersion "23.0.2"
// ...
// ...
defaultConfig {
// Just for example
minSdkVersion 14
// Just for example
targetSdkVersion 23
// This is the main idea
buildConfigField('String', 'MY_SUPER_HOST', "\"${mysuperhost}\"")
// ...
// ...
}
// ...
// ...
}
// ...
// ...
After that build your project and you are able to use your value via BuildConfig.MY_SUPER_HOST

Your statement about being unable to use BuildConfig is not entirely accurate, as you can use Java reflection to find the public static members of BuildConfig as long as you know its fully qualified package.
Say the full package name of your generated BuildConfig is com.company.app.BuildConfig. You can get its Class object with:
Class<?> klass = Class.forName("com.company.app.BuildConfig");
Then you can use that Class object to pick out the fields of it by name:
Field field = klass.getDeclaredField("BUILD_TYPE");
Then you can get its value:
String value = field.get(null);

Related

How to assign API key in manifest from Constant Value class?

I am trying to assign value to below meta in manifest.
currently i have assign value from string.xml class.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value= "#string/MAPS_API_KEY" />
But I want Some thing like this..
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value= com.packagename.MyConstantInterface.MAPS_API_KEY />
I have search a lot, but haven't find a good solution.
NOTE: I am getting all APIs keys from server, storing keys in snappy db and then assigning keys from snappy db to MyConstantInterface.
STEP 1: Create a file named secrets.properties in the main folder (i.e below local.properties, app, build, gradle, README.md,etc.
STEP 2: Paste your API Key in secrets.properties (i.e GOOGLE_API_KEY, FACEBOOK_APP_ID, etc)
STEP 3: Sync the project or Rebuild.
STEP 4: Open build.gradle (app) and create a def function to access the key declared in the secrets.properties.
def getApiKey(){
def Properties props = new Properties()
props.load(new FileInputStream(new File('secrets.properties')))
return props['GOOGLE_MAPS_API_KEY']
}
STEP 5: Create a variable for the function getApiKey() in defaultConfig using manifestPlaceholders to use it in AndroidManifest.xml
defaultConfig {
defaultPublishConfig 'debug'
applicationId "YOUR_APPLICATION_ID"
minSdkVersion 19
targetSdkVersion 27
versionCode 1000
versionName '0.1.0'
manifestPlaceholders = [ GOOGLE_MAPS_API_KEY:getApiKey()]
}
You’re good to go. Now GOOGLE_MAPS_API_KEY variable is public and can be used in AndroidManifest.xml like below
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="${GOOGLE_MAPS_API_KEY}" />
manifestPlaceholders — It helps to create a global variable that can be used only in AndroidManifest.xml
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt')
, 'proguard-rules.pro'
}
applicationVariants.all { variant ->
variant.buildConfigField "String", "GOOGLE_MAPS_API_KEY"
, "\""+getApiKey()+"\""
}
}
And, you can use GOOGLE_MAPS_API_KEY in Java or Kotlin classes like
BuildConfig.GOOGLE_MAPS_API_KEY
Finally, don’t forget to add secrets.properties to your .gitignore file.
Solution was gotten from This Medium post by Chandrasekar Kappusamy
You simply can not simply use a java variable.
Instead of it, You need to inject build variables into the manifest
Declaration:
defaultConfig {
...
manifestPlaceholders = [MAPS_API_KEY_FOR_MANIFEST: "your_maps_key_here"] // TO use in manifest file
buildConfigField "String", "MAPS_API_KEY", '"your_maps_key_here"' // TO use in java file
}
Use in AndroidManifest.xml:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value= "${MAPS_API_KEY_FOR_MANIFEST}" />
Java file Usage:
BuildConfig.MAPS_API_KEY
For more information, You can have a look at this and this.

Cannot complete build because of serializationVersionUID warning

We are currently using greenDAO3 in this project. I believe we were using the greenDAO2 at some point because it seems that we were using the legacy generator class.
So I am attempting to add a new table to the database for a new feature in our application. I am not very familiar with greenDAO, but I figured it would be easier to have it auto-generate the file at build time with Gradle.
Everything works fine, but after adding some stuff to my root.gradle and app.gradle, I get this error.
ERROR: Found 1 problem(s) parsing "/Users/Dustin/Projects/project/app/src/main/java/com/package1/package2/db/MyClassTest.java". First problem:
Pb(96) The serializable class MyClassTest does not declare a static final serialVersionUID field of type long (536871008 at line 18).
These are the changes I made.
diff --git a/app/build.gradle b/app/build.gradle
index 40b3b80d..60f2a688 100644
--- a/app/build.gradle
+++ b/app/build.gradle
## -1,4 +1,7 ##
apply plugin: 'com.android.application'
+apply plugin: 'com.google.gms.google-services'
+apply plugin: 'org.greenrobot.greendao'
+apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
android {
## -234,4 +237,7 ## dependencies {
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
-apply plugin: 'com.google.gms.google-services'
\ No newline at end of file
+greendao {
+ schemaVersion 24
+}
+
When I suppress warnings it proceeds to the next serializable class in the db folder. I really don't want to suppress warnings, because that seems like bad practice in this case.
Add a serialVersionUID field in your MyClassTest.java
A good pratice might be to set the last modification date
public class MyClassTest {
private static final long serialVersionUid = 6082019L;
}
More informations available on this post

Android System.loadLibrary crashing

I'm trying to include a c file, ImageProc into my java file to use it's functions.
I got the code from a MjpegInputStream file (where everything is supposed to work, but of course its never that easy)
Here is the code that crashes (somehow the catch isn't catching it)
static {
try {
System.loadLibrary("ImageProc");
}
catch (Exception e){
e.getMessage();
}
}
The makefile is:
include $(CLEAR_VARS)
LOCAL_MODULE := ImageProc
LOCAL_SRC_FILES := ImageProc.c
LOCAL_LDLIBS := -llog -ljnigraphics
LOCAL_SHARED_LIBRARIES := prebuilt-libjpeg
LOCAL_C_INCLUDES := external/include jni/external/include
So to my understanding I should just be able to use ImageProc.
I know it went through and compiled the c file because at first it couldn't find the h file references (fixed now).
One other thing i'm not sure about is that I call the function pixeltobmp which in the c file is defined as Java_com_camera_simplemjpeg_MjpegInputStream_pixeltobmp which strikes me as odd. I tried changing the name of the method to include the package i'm using rather than the one I copied it from, but that didn't fix anything.
Any help is appreciated.
Additional info: I'm using gradle build 2.10
1. Compile your library
2. Check if you have the .so compiled library(this is important!)
3. In your gradle file add this:
android {
compileSdkVersion 23
buildToolsVersion "22.0.1"
defaultConfig {
minSdkVersion 18
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
sourceSets.main {
jni.srcDirs = []
File configFile = file('pathToYourLibsFolder')
jniLibs.srcDir configFile.absolutePath
}
Then it should work.
In build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
...
}
buildTypes {
...
}
ndk {
moduleName "ImageProc"
// stl "stlport_static"
// ldLibs "log"
}
}
}
As an alternative option, the code that you're using can be easily modified to remove the dependency on OpenCV (or it can now 2 years after you asked the question).
MjpegInputStream.java has two relevant methods, readMjpegFrame() and readMjpegFrame(Bitmap bmp).
Only the later relies on OpenCV and therefore the native library dependency. If you modify the code to remove this method, and then remove:
static {
System.loadLibrary("ImageProc");
}
public native int pixeltobmp(byte[] jp, int l, Bitmap bmp);
public native void freeCameraMemory();
You will no longer have this problem and can still use readMjpegFrame() to get the content you want.
Whether this is less performant, I'm not certain, but it's working fine in my use case.

Gradle DSL method not found: storeFile()

I'm using Android Studio 1.1.0. When I try to sync my Gradle file, I get the following error:
Gradle DSL method not found:storeFile()
Here is my gradle configuration:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "skripsi.ubm.studenttracking"
minSdkVersion 16
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
signingConfigs {
release {
storeFile (project.property("Students_tracking_keystore.jks") + ".keystore")
storePassword "####"
keyAlias "####"
keyPassword "#####"
}
}
}
Can anyone help?
A couple of things to note:
The storeFile DSL method has the following signature:
public DefaultSigningConfig setStoreFile(File storeFile)
i.e. it expects a File to be passed in. You probably need to place a File constructor in your code to ensure you are actually creating a File object. Because you're currently not passing in a file, Gradle is complaining that it can't find a method with the appropriate signature.
Secondly, you are currently appending two suffices to the filename: .jks and .keystore. You should only include one of these based on the suffix of the file you are referencing (it's probably .jks, but you should check to be sure).
In short, one of the following replacement lines will probably work for you:
storeFile file(project.property("Students_tracking_keystore") + ".keystore")
or
storeFile file(project.property("Students_tracking_keystore") + ".jks")
or
storeFile file(project.property("Students_tracking_keystore.keystore"))
or
storeFile file(project.property("Students_tracking_keystore.jks"))

Android Studio (0.8.2) + Android Annotations (3.0.1) cannot symbol class MyClass

I have this problem with the annotations for few days...
Error:(13, 26) cannot find symbol class LoginActivityAnnotations_
But the annotation class exist and the class import in my MainActivity work greate
http://imagizer.imageshack.us/v2/150x100q90/911/x8RzRM.png
The annotaitons classes were generated correctly in this directory:
http://imagizer.imageshack.us/v2/150x100q90/538/bEplNx.png
This is my build.grandle file
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:+'
}
}
apply plugin: 'android'
apply plugin: 'android-apt'
repositories {
mavenCentral()
mavenLocal()
}
apt {
arguments {
resourcePackageName "com.ar.sdocs"
androidManifestFile variant.processResources.manifestFile
}
}
dependencies {
compile 'com.android.support:appcompat-v7:20.0.0'
compile 'com.android.support:support-v4:20.0.0'
apt "org.androidannotations:androidannotations:+"
compile 'org.androidannotations:androidannotations-api:+'
compile 'com.nhaarman.listviewanimations:library:2.6.0'
compile files('libs/commons-lang3-3.3.1.jar')
compile 'com.google.android.gms:play-services:4.3.+'
compile files('libs/joda-time-2.3.jar')
compile files('libs/bcprov-ext-jdk15on-150.jar')
compile files('libs/bugsense-3.6.1.jar')
compile 'org.apache.httpcomponents:httpcore:4.3.2'
compile 'org.apache.httpcomponents:httpmime:4.3.4'
compile 'com.google.code.gson:gson:2.2.4'
compile files('libs/json-simple-1.1.1.jar')
apt "org.androidannotations:androidannotations:+"
compile 'org.androidannotations:androidannotations-api:+'
}
android {
compileSdkVersion 19
buildToolsVersion '19.1.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 19
versionCode 1
versionName '0.1'
}
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
}
}
android.applicationVariants.each { variant ->
aptOutput = file("${project.buildDir}/generated/source/apt/${variant.dirName}")
println "****************************"
println "variant: ${variant.name}"
println "manifest: ${variant.processResources.manifestFile}"
println "aptOutput: ${aptOutput}"
println "****************************"
variant.javaCompile.doFirst {
println "*** compile doFirst ${variant.name}"
aptOutput.mkdirs()
variant.javaCompile.options.compilerArgs += [
'-processorpath', configurations.apt.getAsPath(),
'-AandroidManifestFile=' + variant.processResources.manifestFile,
'-s', aptOutput
]
}
variant.addJavaSourceFoldersToModel(aptOutput)
}
But every time I run a build, I get the error I mentioned before. I'm trying different configurations days ago but I can not find one that works
Thats the complete error (I only import the annotations class)
Error:(14, 26) cannot find symbol class LoginActivityAnnotations_
Note: Resolve log file to /Users/CARRY/AndroidStudioProjects/sdocs/SDocs/build/generated/source/apt/androidannotations.log
Note: Initialize AndroidAnnotations 3.0.1 with options {resourcePackageName=com.ar.sdocs, androidManifestFile=/Users/CARRY/AndroidStudioProjects/sdocs/SDocs/build/intermediates/manifests/debug/AndroidManifest.xml}
Note: Start processing for 5 annotations on 145 elements
Note: AndroidManifest.xml file found with specified path: /Users/CARRY/AndroidStudioProjects/sdocs/SDocs/build/intermediates/manifests/debug/AndroidManifest.xml
Note: AndroidManifest.xml found: AndroidManifest [applicationPackage=com.ar.sdocs, componentQualifiedNames=[com.ar.sdocs.main.MainActivity, com.ar.sdocs.login.LoginActivity, com.ar.sdocs.dashboard.DashboardActivity, com.ar.sdocs.login.registro.RegistroActivity, com.ar.sdocs.dashboard.settings.editar.SettingsUserEditActivity, com.ar.sdocs.dashboard.upload.UploadActivity, com.ar.sdocs.dashboard.materias.main.MateriaActivity, com.ar.sdocs.util.media.FilePickerActivity, com.ar.sdocs.gcm.GcmIntentService, com.ar.sdocs.gcm.GcmBroadcastReceiver], permissionQualifiedNames=[android.permission.USE_CREDENTIALS, android.permission.GET_ACCOUNTS, android.permission.READ_PROFILE, android.permission.READ_CONTACTS, android.permission.INTERNET, android.permission.WAKE_LOCK, com.google.android.c2dm.permission.RECEIVE, android.permission.CAMERA, android.permission.READ_EXTERNAL_STORAGE, com.example.gcm.permission.C2D_MESSAGE], applicationClassName=null, libraryProject=false, debugabble=false, minSdkVersion=14, maxSdkVersion=-1, targetSdkVersion=19]
Note: Found project R class: com.ar.sdocs.R
Note: Found Android class: android.R
Note: Validating elements
Note: Validating with EActivityHandler: [com.ar.sdocs.login.LoginActivityAnnotations]
/Users/CARRY/AndroidStudioProjects/sdocs/SDocs/src/main/java/com/ar/sdocs/login/LoginActivityAnnotations.java
Warning:(45, 1) The component LoginActivityAnnotations_ is not registered in the AndroidManifest.xml file.
Note: Validating with ViewByIdHandler: [emailEditText, passwordEditText]
Note: Validating with ClickHandler: [loginButtonClicked(), registerButtonClicked()]
Note: Validating with TouchHandler: [loginRelativeLayoutTouched(android.view.View,android.view.MotionEvent)]
Note: Validating with AfterViewsHandler: [verificarLogin()]
Note: Processing root elements
Note: Processing root elements EActivityHandler: [com.ar.sdocs.login.LoginActivityAnnotations]
Note: Processing enclosed elements
Note: Number of files generated by AndroidAnnotations: 1
Note: Writting following API classes in project: []
Note: Generating class: com.ar.sdocs.login.LoginActivityAnnotations_
Note: Time measurements: [Whole Processing = 148 ms], [Process Annotations = 32 ms], [Generate Sources = 31 ms], [Find R Classes = 24 ms], [Extract Annotations = 23 ms], [Validate Annotations = 16 ms], [Extract Manifest = 11 ms],
Note: Finish processing
Note: Start processing for 0 annotations on 1 elements
Note: Time measurements: [Whole Processing = 3 ms],
Note: Finish processing
Note: Start processing for 0 annotations on 0 elements
Note: Time measurements: [Whole Processing = 1 ms],
Note: Finish processing
Warning:Unclosed files for the types '[dummy1407025286017]'; these types will not undergo annotation processing
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Information:BUILD SUCCESSFUL
Information:Total time: 21.886 secs
Information:1 error
Information:4 warnings
Information:See complete output in console
I could be because you havn't included the LoginActivityAnnotations_ file where you use it - because Android Studio does not help you with that. I had that problem.
You need to make an include of the package where the LoginActivityAnnotations file.
If you were using this include, to get the file without the underscore:
com.example.LoginActivityAnnotations
Then use this one:
com.example.* //To load LoginActivityAnnotations_
(The include will be grey and you will still be left with red words but it will compile)

Categories

Resources