I can't open my class just find a BuildConfig file - java

For unknown reason a java file in an android studio project
has a sub arrow to BuildConfig class from an other package of an other project
/**
* Automatically generated file. DO NOT MODIFY
*/
package alsayed.aly.maintenanceplaner;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "alsayed.aly.maintenanceplaner";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
I tried to revert it but it is not working as the file just created now.

At build time, Gradle generates the BuildConfig class so your app code can inspect information about the current build.
You can also add custom fields to the BuildConfig class from your Gradle build configuration file using the buildConfigField() method and access those values in your app's runtime code. Likewise, you can add app resource values with resValue().
android {
...
buildTypes {
release {
// These values are defined only for the release build, which
// is typically used for full builds and continuous builds.
buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
resValue("string", "build_time", "${minutesSinceEpoch}")
...
}
debug {
// Use static values for incremental builds to ensure that
// resource files and BuildConfig aren't rebuilt with each run.
// If they were dynamic, they would prevent certain benefits of
// Instant Run as well as Gradle UP-TO-DATE checks.
buildConfigField("String", "BUILD_TIME", "\"0\"")
resValue("string", "build_time", "0")
}
}
}
In your app code, you can access the properties as follows:
Log.i(TAG, BuildConfig.BUILD_TIME);
Log.i(TAG, getString(R.string.build_time));

Related

Replacing a string within a .class file on build with Gradle Kotlin

I've got a Java application with the following variable:
static final String MAGIC_VERSION = "SET_BY_MAGIC";
Using gradle, I want to replace this on runtime with my gradle project version, however I am having issues replacing the string.
This is my gradle file:
tasks {
processResources {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
from(sourceSets["main"].java) {
filter {
it.replace("SET_BY_MAGIC", version as String)
}
}
}
}
What am I doing wrong?

(Android Unity plugin) i created a simple plugin, expected 123, got 0

I'm trying to make a plugin for Unity, but not even the simplest class works.
In Android Studio I created a library module, and in it, the following class:
package com.vuforia.android.pluginlib;
import static android.os.Looper.getMainLooper;
public class Multi {
static public Multi mult=new Multi();
static public int testes =123;
}
After that I added to the gradle of lib, the following configurations of a Task,to create the aar:
task copyPlugin (type : Copy){
dependsOn assemble
from ('build/outputs/aar')
into ('../../Assets/Plugins/Android')
include(project.name+'-release.aar')
}
In unity, I created some sprite, and added such script to it:
using UnityEngine;
public class movetest : MonoBehaviour
{
private AndroidJavaClass javaClass = null;
void Update()
{
javaClass = new AndroidJavaClass("com.vuforia.android.pluginlib.Multi");
int i = javaClass.GetStatic<int>("testes");
Debug.Log("->>"+i);
}
}
and when clicking on run, then what is received "- >>0".
I assume you are running in the editor because you stated "when clicking on run"..
Java plugins will not work in the editor. You would need to deploy to an Android device to test the functionality.

Calling a class variable into build.properties

I'm sort of testing/ correcting and old gradle project to build an RPM with a tool that automatizes the import of files to a server without doing it by hand.
However this tool requires a file that is used by this proprietary software and uses it do know which dirs and libs are needed to be used. And at this point is necessary to generate the RPM and copy the file by hand the the tool's bin folder and I wanted to incorporate that file into the RPM without passing the full path to the file since the software can be used by anyone and the dirs for the software might be different from environment to environment.
On of the classes has the following variables declared:
private static final String DB_USER = "db_user";
private static final String DB_PASSWORD = "db_password";
private static final String DB_URL = "db_url";
private static final String W_HOME = "w_home";
private static final String W_LOGIN = "w_login";
private static final String W_LOGIN_USERNAME = "username";
private static final String W_LOGIN_PASSWORD = "password";
private static final String W_SERVER_URL = "w_server_url";
The w_home is the path used to read where the software is installed and by using that variable in the build.gradle I could easily pass the folders and the file name and get it into the RPM package.
My question if its even possible to call java variables or the get of that variable into the build.gradle
Edit: adding the gradle task
task buildRpm(type: Rpm, overwrite: true, dependsOn: build) {
packageName = applicationName
release = rpm_release
arch = NOARCH
os = LINUX
epoch = git.head().time
summary = "Import"
license = 'Proprietary'
user User
permissionGroup Group
//THIS DIRECTORY SHOULD ALREADY BE PRESENT
into(Home){
addParentDirs = false
fileMode 0644
dirMode 0755
directory("${Home}/${ packageName }")
directory("${Home}/${ packageName }/lib")
directory("${Home}/${ packageName }/config")
directory("${Home}/${ packageName }/bin")
directory("${Home}/${ packageName }/logs", 0777)
from(jar.outputs.files) {
into "${ packageName }/lib"
}
from(configurations.runtime) {
into "${ packageName }/lib"
}
from('lib') {
into "${ packageName }/lib"
}
from('src/dist/config') {
exclude 'log4j2.xml'
into "${ packageName }/config"
}
from('src/dist/config/log4j2.xml') {
into "${ packageName }/config"
fileType CONFIG | NOREPLACE
}
from('out/scripts') {
into "${ packageName }/bin"
fileMode 0755
}
}
requires('java', '2000:1.8.0_121', GREATER | EQUAL)
}
If the class containing the constants is part of your project, one way to achieve your goal would be to dynamically load the output jar in your RPM generating task then extract the desired values via reflection :
// Put this in your RPM task
URL[] urls = [new URL("file:///" + jar.archivePath.absolutePath)]
def loader = new URLClassLoader(urls)
// className is the fully qualified name of the configuration class
Class<?> clazz = loader.loadClass(className)
def field = clazz.getDeclaredField("W_HOME")
field.setAccessible(true) // This is needed for private fields
String home = field.get(null)
Since your class has constants that are apparently intended to be used externally, there is no point in making them private.
Of course, you'll have to adapt the above snippet if you have some custom build chain that does not use the standard jar task.

Jeta: How to create custom annotation processors

There is plenty of features that already available on Jeta, but what if something is missing. Can I create my own annotations and generate metacode for them?
Needed a step-by-step tutorial how to create custom Jeta processors.
How to create custom processors, step-by-step tutorial
Step 1: Hello, World project
For this tutorial let's create a simple Gradle project with one module app and with a single class SayHelloApp. This class writes Hello, World! to standard output.
For the illustration we are going to create Hello annotation that sets Hello, Jeta! string to the annotated fields.
Step 2: common module
First, we need a module that will be accessible in app and apt (will create shortly) modules. In common module we need two classes - Hello annotation and HelloMetacode interface:
Step 3: apt module
apt - is a module in which we'll create all the required for code generation classes. For this tutorial we need a processor that will handle our Hello annotation.
Note that this module depends on common module so we used Hello annotation as a parameter for the super constructor. By doing that we're saying to Jeta that we need all the elements annotated with given type. The module also depends on jeta-apt in order to get access to the Jeta classes.
Step 4: Processor
Created SayHelloProcessor now does nothing. Let's add some logic in it. The idea here is to generate java code that sets Hello, Jeta string to the fields annotated with Hello.
Note that Jeta uses JavaPoet to create java source code. It's really great framework by Square. Please, check it out on GitHub.
First, we need that our metacode implements HelloMetacode. To do that we'll add super interface to the builder:
MetacodeContext context = roundContext.metacodeContext();
ClassName masterClassName = ClassName.get(context.masterElement());
builder.addSuperinterface(ParameterizedTypeName.get(
ClassName.get(HelloMetacode.class), masterClassName));
Next, implement HelloMetacode by creating void setHello(M master) method:
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("setHello")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addParameter(masterClassName, "master");
Finally, the statements for each element annotated with Hello, that Jeta passes in process method via roundContext parameter:
for (Element element : roundContext.elements()) {
String fieldName = element.getSimpleName().toString();
methodBuilder.addStatement("master.$L = \"Hello, Jeta\"", fieldName);
}
Here is the complete SayHelloProcessor listing:
package org.brooth.jeta.samples.apt;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;
import org.brooth.jeta.apt.MetacodeContext;
import org.brooth.jeta.apt.RoundContext;
import org.brooth.jeta.apt.processors.AbstractProcessor;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
public class SayHelloProcessor extends AbstractProcessor {
public SayHelloProcessor() {
super(Hello.class);
}
#Override
public boolean process(TypeSpec.Builder builder, RoundContext roundContext) {
MetacodeContext context = roundContext.metacodeContext();
ClassName masterClassName = ClassName.get(context.masterElement());
builder.addSuperinterface(ParameterizedTypeName.get(
ClassName.get(HelloMetacode.class), masterClassName));
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("setHello")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addParameter(masterClassName, "master");
for (Element element : roundContext.elements()) {
String fieldName = element.getSimpleName().toString();
methodBuilder.addStatement("master.$L = \"Hello, Jeta\"", fieldName);
}
builder.addMethod(methodBuilder.build());
return false;
}
}
Step 5: Metacode
All the required for code generating classes are created and we're ready to try. But first, we need to add jeta.properties file in order to configurate Jeta. You can find more details about this file on this page. The file should be located in the root package. For our tutorial its content would be:
metasitory.package=org.brooth.jeta.samples
processors.add=org.brooth.jeta.samples.apt.SayHelloProcessor
Next, modify SayHelloApp. Instead of initializing text field we'll put Hello annotation on it:
public class SayHelloApp {
#Hello
String text;
}
And build.gradle:
group 'org.brooth.jeta-samples'
version '1.0'
buildscript {
repositories {
maven {
url 'https://plugins.gradle.org/m2/'
}
}
dependencies {
classpath 'net.ltgt.gradle:gradle-apt-plugin:0.5'
}
}
apply plugin: 'net.ltgt.apt'
apply plugin: 'java'
sourceCompatibility = 1.7
repositories {
mavenCentral()
jcenter()
}
compileJava {
options.sourcepath = files('src/main/java')
}
dependencies {
apt project(':apt')
compile project(':common')
compile 'org.brooth.jeta:jeta:+'
}
Now we're ready to generate metacode. Run next command in your console:
./gradlew assemble
If there is no problems so far, we'll see SayHelloApp_Metacode file under app/build directory:
Step 6: Controller
Controllers are the classes that apply metacode to the masters. Let's create one for HelloMetacode in app module:
package org.brooth.jeta.samples;
import org.brooth.jeta.MasterController;
import org.brooth.jeta.metasitory.Metasitory;
public class SayHelloController<M> extends MasterController<M, HelloMetacode<M>> {
public SayHelloController(Metasitory metasitory, M master) {
super(metasitory, master, Hello.class, false);
}
public void setHello() {
for (HelloMetacode<M> metacode : metacodes)
metacode.setHello(master);
}
}
Step 7: MetaHelper
MetaHelper is a simple static-helper class. You shouldn't use it in your project if you are not comfortable with static helpers. You can read more details about this class on this page.
Anyway, let's create MetaHelper in app module:
package org.brooth.jeta.samples;
import org.brooth.jeta.metasitory.MapMetasitory;
import org.brooth.jeta.metasitory.Metasitory;
public class MetaHelper {
private static MetaHelper instance;
private final Metasitory metasitory;
public static MetaHelper getInstance() {
if (instance == null)
instance = new MetaHelper("org.brooth.jeta.samples");
return instance;
}
private MetaHelper(String metaPackage) {
metasitory = new MapMetasitory(metaPackage);
}
public static void setHello(Object master) {
new SayHelloController<>(getInstance().metasitory, master).setHello();
}
}
Note that we must pass to MapMetasitory the same package ("org.brooth.jeta.samples") that we specified as metasitory.package in jeta.properties.
Step 8: Usage
The last step - we invoke our MetaHelper's method. Here is the complete listing of SayHelloApp:
package org.brooth.jeta.samples;
public class SayHelloApp {
#Hello
String text;
public SayHelloApp() {
MetaHelper.setHello(this);
}
public void sayHello() {
System.out.print(text);
}
public static void main(String[] args) {
new SayHelloApp().sayHello();
}
}
Finally, we can run SayHelloApp. In the console we should see:
Hello, Jeta
Links
This tutorial on GitHub
Jeta Website
Jeta on Android
Happy code-generating! :)

Suddenly error ObjectSetting.java file after importing existing project on eclipse

I'm making a Auto SMS sender app on android,
Last time my app is working fine, but suddenly I've to delete the project form my eclipse, for this I wanna again import this project,
After importing this project my app is not working, showing lots of error on Object file.
Please check the screenshot http://prntscr.com/75v2cg
Here is my code
package com.example.serviceexample.model.object;
import java.io.Serializable;
public class ObjectSetting extends Object implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int setting_id;
private String setting_name;
private String setting_value;
public int getSetting_id() {
return setting_id;
}
public void setSetting_id(int setting_id) {
this.setting_id = setting_id;
}
public String getSetting_name() {
return setting_name;
}
public void setSetting_name(String setting_name) {
this.setting_name = setting_name;
}
public String getSetting_value() {
return setting_value;
}
public void setSetting_value(String setting_value) {
this.setting_value = setting_value;
}
public ObjectSetting() {
this.setting_id = 0;
this.setting_name = "";
this.setting_value = "";
}
public ObjectSetting(String name, String value) {
this.setting_id = 0;
this.setting_name = name;
this.setting_value = value;
}
public ObjectSetting(int id, String name, String value) {
this.setting_id = id;
this.setting_name = name;
this.setting_value = value;
}
}
Try setting the java build path . Installed jre needs to be reset in eclipse project properties. As you can see its showing error for java.io and String Class itself .
Frist of all Check your Eclipse preferences. window -> preferences -> Java -> Installed JREs . The installed Jre you're using should be marked there. Also check your project's build path: Right click on the project -> Properties -> Java Build Path. then check in the "libraries" folder whether the JRE System Library is present and if not add it using "Add library"->"JRE System Library" and then select the correct one from an installed JDK (Alternate Jre).

Categories