Intellij & Gradle module file name - java

I'm trying to move an existing project to gradle from ant. I'm using Intellij 13, and I've managed to get one module running under gradle by deleting the iml file. However, it insists on writing an iml file that has a name that matches the directory name not the module name.
I recognize that this is probably not a problem for folks who work alone or on a single team in a large company where the IDE and version is handed down from on high. However this project involves a variety of contractors from several companies who all supply their own IDE's. Intellij's licensing model makes it impractical to supply the IDE to outside contractors because most work is done off site and there is no way to take back or de-authorize the license key once you give it out.
Since upgrading Intellij is not free, it's nearly impossible to coordinate everyone to upgrade at once and so I use the file based project format, with a project file named ourproject.ij12.ipr1 and another named ourproject.ij13.ipr and the iml files for the module in the directory foo are foo.ij12.iml and foo.ij13.iml
This works great, and the policy is that everyone has until 14 comes out to get off of 12 so that we don't get an infinite number of versions going, but we don't have to synchronize our upgrades too the nanosecond either.
Unfortunately, as soon as I try to use build.gradle in the foo directory in intellij, it writes foo.iml which totally breaks the forgoing conventions. Furthermore, it adds another module (without asking) and that leads to two modules in the same directory and the ide won't let you change either one because two modules in the same directory are an error.
Can anyone tell me how to influence the file name that Intellij writes for the iml file when using gradle? obviously having separate directory names is not going to do it unless I get very elaborate with symlinks and ant.symlinks task, and that won't work if anyone trys to run it natively on windows.
EDIT: Since folks seem to be in the habit of deleting their unaccepted answers, let me clarify. I am aware of the gradle idea eclipse plugins. I am not asking for a guide to IDE agnosticism. I find there are things of value in IDE setups, and want to share them among others using the same IDE (where "same" includes the version, cross version sharing is not expected, but more than one version at a time is).
To be more specific, I am looking for one of these:
A configuration or trick that allows me to control the file names of iml files
Another way to maintain two versions of ide files, that is not too byzantine.
Confirmation from one of the JetBrains folks who participates in SO that there is no longer a way accomplish my goal with IDEA.
EDIT2: Solutions involving gradle generating the files are not going to work. Intellij 13 changes the file name to match the directory name not the module name, which is the soruce of the problem. I need a solution that convinces Intellij not to do that. I had no problems before the upgrade to 13.

Using the idea plugin I was able to get it to generate two iml files for me based on a commandline parameter. Here is the (minimal) build.gradle file I created
apply plugin: 'java'
apply plugin: 'idea'
def imlName = name + (hasProperty('generate12') ? '.ij12' : '.ij13')
idea {
module {
name = imlName
}
}
This script will generate a '13' file for you by default. So to change that you will need to set the generate12 property.
Commands I ran:
> gradle idea
> gradle idea -Pgenerate12=true
> ls
build.gradle test.ij12.iml test.ij13.iml test.ipr test.iws
The idea module documentation might have some more useful things for you.
Side note:
I think it would be best if you gave the project without iml files to everyone and told them to run gradle idea(without the custom iml name stuff) to let the files be created. This will allow you to not have to maintain files that will get modified and overwritten by IntelliJ. We check in iml files and it causes nothing but problems when someone checks something in and breaks it for everyone.

Use settings.gradle file to change module names. Intellij should use it.
Next, you can use gradle.properties to set your prefix.
E.g.
setting.gradle:
rootProject.name = adjustName("ourproject")
include "someProject"
// ... other includes
rootProject.children.each{ it.name=adjustName(it.name)}
String adjustName(String name) {
String pref = System.properties['myIdeaVersionPrefix']
return pref != null ? name + "." + pref : name
}
gradle.properties:
systemProp.myIdeaVersionPrefix=ij13
see screenshot for the configuration at http://i.stack.imgur.com/CH2Bv.png

There doesn't seem to be a good answer for this. I have filed this as a bug in YouTrack http://youtrack.jetbrains.com/issue/IDEA-119625.

Related

tink library com.google.protobuf.GeneratedMessageV3$ cannot be resolved

I recently tried to add the google tink library to eclipse and it always has a "com.google.protobuf.GeneratedMessageV3$ cannot be resolved" error, I normally never have any problems with adding libraries to my project, and from what I can tell it has something to do with the all key template files since the error only occours when I try to generate a new KeysetHandle with any key template, and the error only starts when i enter in the key template file# https://github.com/Gameidite/testProject
The Protobuf library can generate Java classes for you. You need to find where these .class files have been output to (eg there should be a GeneratedMessageV3$.class somewhere) and make sure that they are included on your classpath. There's presumably somewhere in Eclipse where you can configure where it looks for class files - you'll need to add the generated files there.
If the generated class files don't exist yet you need to figure out what to do to generate them. It might be easier to use Maven or Gradle as suggested in the Tink documentation rather than directly adding things to Eclipse.
I think it's probably because Eclipse cannot find the protobuf Java runtime. Have you tried adding Tink to your project with Maven or Gradle?

Android Studio 3.1.3 - Unresolved reference: R - Kotlin

I am new to kotlin, i have converted some code from java but it seems like there's something wrong, The R in findViewById(R.id.my_id) is highlighted in red and it shows this message : "Unresolved reference: R".. I've been looking for a solution but i seem not to figure it out, So what should i do?
Here's a screenshot :
The issue can be caused by many factors,
as mentioned by martomstom in this Answer the issue is sometimes caused by com.android.tools.build:gradle version, changing it's version to a more stable one would solve the problem: for example: com.android.tools.build:gradle:3.4.0-alpha02 with com.android.tools.build:gradle:3.2.1
Also, having libraries from the same group, but with different versions may cause the problem or even more runtime errors. use the exclude group method like the following : implementation('com.squareup.picasso:picasso:2.71828') { exclude(group: 'com.android.support') } in this case, picasso library uses android.support components, the android library version used in picasso is different than the one you're currently using in your app, so in order to solve this issue, we have to exclude it completely from its sub library and class groups.
It can also happen by the mismatch of resources and code, including this importation line in your activity may solve the problem too : import com.package.name.R
Sometimes it can happen because of the IDE, performances or memory.. Cleaning the project from time to time may save you some time, on Android Studio it would be something like this : Build -> Clean Project / Rebuild Project - Cleaning IDE cash also helps with performance and memory, on Android Studio it would look like this : File-> Invalidate Chases/ Restart -> Invalidate Cashes and Restart
I noticed that this problem happens to me the most of the time when importing new resources, Using prohibited characters in their names would fire the error, such as . , , - , UpperCase or special Letters
And as a suggestion , if you're using Kotlin, i really recommend using Kotlin extensions in your activity such as : import kotlinx.android.synthetic.main.activity_page.* or if you're using a custom view : kotlinx.android.synthetic.main.view_layout.view.*
after that, in onCreat() method of an activity , you'll only have to call the id, for example : my_edit_text_ID.text = "Kotlin Dbest!", or from a custom view : mCostumView.my_edit_text_ID.text = "Kotlin Dbest!"
EDIT :
I have faced this issue againe and the problem was the '' R '' library was imported from 2 different sources :
com.android.R
com.example.package.R
You must only import the '' R '' library with your application package name,
in this case com.example.package.R
Sometimes the library is not imported at all, to import it, click on the
unresolved reference R and press Alt + Enter
EDIT:
As tobltobs mentioned in the comments section: " Most of the time the problem is caused by another error which prevents the build system from creating generated sources. To find the root cause look at the gradle log (the "toggle view" icon below of the green hammer in the Build output) and look for errors unrelated to R or BuildConfig (also generated). If there is no other error left and the problem with R persists then maybe something of this list might help. "
EDIT:
As Patrick Beagan mentioned, Kotlin extensions are now deprecated - I'd advise using ViewBinding instead
I used com.android.tools.build:gradle:3.3.0-alpha13 and had the same issue. Changing to stable Version 3.2.1 solved this problem for me.
So this is a misleading error.
The fastest way to get to the root cause is to run:
bash gradlew assembleDebug --debug
then scroll up and look for the real error happening.
However, if it still doesn't seem like you have the answer you are looking for, then read on.
I'm going to explain the 30,000 foot view of what is happening. This is not EXACT order or EXACT flow, it is just pretty damn close ;) so if you know more then I do of the exact order and care to make corrections with links, feel free I won't stop ya :).
The Process
The R file is generated code.
There is an order to the generation.
Gradle will do it's magic, pull it's dependencies and kick off it's
warning and error tree first,
then Android converts all Kotlin to Java behind the scenes. Yup that's
right, our beloved Kotlin still has to be Java to compile for our
beloved ART virtual machine.
Then it runs through and does the adapters that you have created for
JVM Statics and a few other tasks.
Next up it compiles all the xml databinding files first to create the
generated databinding files.
If everything succeeds it moves on to processing the assets and
resources. Which creates pointers or IDs for each resource that you
reference in code. Next it will run through and begin compiling the
code and packaging process after that.
Pretty straight forward process, but here in lies the problem.
The misleading Error
If any step fails before the R generation is complete, then the R does not get generated. Sometimes a simple rebuild is all you need to do, sometimes a simple File->Invalidate Cache and Restart is all you need. However, more often than not you have a code issue in your gradle, your xml, your databinding or your adapters that are preventing the compiler from even reaching the R generation stage.
So the next question is
"Well shoot, how do we troubleshoot it if the errors are worthless or
non-existent".
Well first let's talk about the many ways these errors present themselves.
Duplicate Databinding class found
xml Binding Error at line #
Couldn't find matching signature of bind:customAdapterMethod
Can't find R file of the correct project, only shows import options for sub modules or incorrect namespace R files.
Couldn't find DataBindingUtility or DataBinding for activity/fragment
And many other various ways as well, too many to list them all
Next, let's talk about potential candidates causing the problem. As there are sooo many lol.
Gradle Syncing issues
Bad versions of Gradle or Tools, you may have gone too far forward in your last gradle file modification. Try stepping back one version and "invalidate cache and restart" if that fixed it, great, if not, read on.
Caching Issues (File->Restart and Invalidate Cache)
xml elements with wrong namespace
xml elements with bad IDs or references IDs out of order (i.e. you say align to right of an element that is lower in the xml document then the sibling element that is trying to reference it)
xml data binding issues referencing namespace or member that doesn't exist or is not typed correctly
xml data binding issues in non-auto-filled spots like custom attributes using adapters as those are harder to spot. i.e. bind:myCustomMethod=#"myObject.mistypedProperty()"
JVM Static adapters with issues or duplicated signatures
Duplicated or bad character in the Strings or Dimens file or any other xml file for that matter
Private variable marked for #Binding without properties to access it
Member variable marked for #Binding that matches a parent class method causing duplications that manifests itself in almost impossible errors
Mismatch of types like using an adapter that takes (Int) but you are passing (Int?) via data binding and it isn't recognized with JVM Statics until compile time
You selected IMPORT on a popup to import R file of a sub module instead of the application file
Having bindable members in a child or parent class, but not giving fully qualified namespace to class cast in the XML usage of the parent or child class. As the databinding compiler is not smart enough to realize the variable provided for class Foo is also parentFoo baseclass, so you have to qualify it as android:text="#((com.path.parentFoo)foo).parentMethod"
Having a method name in a class, that matches a "generated property from #Binding member variable" i.e. firstName as a variable, but then having a method called getFirstName in a parent or child class, because you are now matching a method name that will get auto generated, thus causing dataBindingUtility duplication class errors.
There are more causes, but this should give you a series of places to look, but the list can go on and on seriously.
Unfortunately this happens a lot in bleeding edge technologies where the UI tools are not up to speed with the terminal based tools yet. So I suggest you run from the project root in a terminal with
bash gradlew assembleDebug --debug
When it fails, and it will. Start scrolling up through the logs until you find the red where you see what is actually failing and preventing the next stage from occurring.
You will find this especially useful when you start dealing with databinding.
TIP:
When you start dealing with databinding, make sure you compile and run often because the goal is to recognize right away before doing other files to make sure you didn't break generation and make your life MUCH easier to know code you just added caused the issue before getting too far.
Times to compile and run to confirm no issues before moving on.
If you add a few JVM statics compile and run
If you add variables to your XML to use
If you bind to properties of your model in 1 file
If you add a binding to a JVMStatic
If you add bindable members or properties to an model
If you refactor moving observable member variables or properties into children or base classes
Any other xml or binding related elements that can effect the generated code.
Like I mentioned above, the reason is to avoid getting so many changes, that it becomes a troubleshooting nightmare to find a generic vague, horrible error related to generated databinding code. I'm sure the tools will improve, but for now, do yourself a favor and compile and run often when changing Databinding related items.
Happy Coding
Use gradle commands.
In Android Studio, on the right menu:
Gradle -> :app -> Tasks -> build -> clean.
After that, Gradle -> :app -> Tasks -> build -> build
I had wrong import statement import android.R instead of import my.project.package.R. Fixing it solved the problem
I had the same problem, and I tried not to downgrade from gradle version 3.3 to gradle version 3.2.1. Instead I updated Android Studio to version 3.3, which made the trick for me ;-)
This worked for me. How much work it is depends on how big your project is. I started a new project, created the required modules (XML, Kotlin, colors, strings, etc.), then copied the code into the modules in the new project from the modules in the old project. Copying XML saves a lot of time compared to recreating the UI. All in all, it take a little while, but I have spent much more time tring to fix the unresolved reference error without it.
TRY THIS
Go to the content_main.xml file and there you need to change the
android:id="#+id/??????"> line of code to whatever id you have given to your file.
Replace question mark ?????? with the related file id name.(IF you dont know the id go to the design tab on the bottom and click on the related Asset.
On the right side below attributes, you can find the ID you have given to it.
If it is blank you can freshly name it and Android Studio will write the code.
Then restart Android Studio. Hope this will help. Happy coding.
I believe that I came across the real answer (though by accident).
I also, as the OP had my KT file fail to location R. as well as other classes that happen to be in java. What I noticed was that there was a case difference I the filenames. Once I corrected the import statements to match the case of the package (aka, folder) the errors resolved.
I had the same problem with R reference too.
Finally Android Studio 3.3 has been released and using 'com.android.tools.build:gradle:3.3.0' the problem has been fixed!
I update Android Studio to version 3.3.1 and solved this problem.
Downgrading gradle version worked for me.
I changed :
Gradle version from : 4.10.4 to 4.4.1
and Gradle Plugin version from : 3.3.1 to 3.1.3
If your are experiencing this issue in Kotlin because you cannot reference the elements of the xml layout by ids. (e.g. R.id.adView) then try removing the line import android.R from your kotlin file.
For me it was because I had created a new package and R wasn't available until I imported it from the package above
I faced the same issue. I restarted my Android Studio, invalidate caches, Sync Gradle but nothing was working. Then I looked into my file and there are 2 imports of my R. 1 import was related to my application package and the other was related to Android.
import com.example.myApp.R
import android.R // This import was added accidentally during the build.
Removing second import related to android solved this issue.
I had an issue because of this import:
import android.os.Build.VERSION_CODES.*
In the latest version it contains R
I had same problem while using auto-manifest plugin. Adding AndroidManifest.xml explicitly solved the problem to me.
I used to File --> Invalidate Caches... and issue resolved.
Just restarting Android Studio solved it for me.
I also had this problem, Gradle Sync, and Invalidate Cache, and Restarting Android Studio Didn't help. Upgrading and Downgrading Gradle were also not helpful.
What worked for me is: Make Project (Ctrl + F9) and then try to run the project.
I solved this error by following Android Studio's lint tools to upgrade the version of a dependency in the project-level gradle file. In this case, I upgraded androidx.navigation:navigation-safe-args-gradle-plugin from 2.3.2 to 2.5.2 (latest version), then synced the project.
Here is the solution,
File->Project Structure->Project, select Android Gradle Plugin Version as 3.2.1 from the drop-down. then click apply.

Eclipse-PMD Configure ruleset globally

So i am using the Plugin Eclipse-PMD (http://sourceforge.net/projects/pmd/files/pmd-eclipse/update-site/) in a shared version control enviroment.
We have multiple smaller projects in the entire project.
Out of the box it seems that this plugin requires individual configuration for every single project.
The way it works it that it searched for a .pmd file in the project and read information from that.
But it's really inconvenient to do that for 10-20 subprojects.
There is a general setting under Preferences -> PMD. But this doesn't seem to apply globally, even if that global checkbox is checked.
What i basically want: I want to configure the plugin to respect a single ruleSet-file in one place.
There is another problem with configuring it subproject-specific: I cannot configure a relative path for the ruleSetFile in the .pmd-file.
The problem with absolute path is that the file is checked into version control ... so with every commit everyone else would have to readjust.
I found this commit: https://github.com/pmd/pmd/pull/36 but i cannot seem to make it work the way it's roughly described.
So, did anyone achieve what i am looking for?
Edit: Actually i cannot even specify any other file that is not ".ruleset" in the .pmd-file as <ruleSetFile> without specifying an absolute path??
The default value for ruleSetFile is ".ruleset". So i thought, analogous to that, i could create a file in the exact same dir, call it fooRules.xml, and specify it via <ruleSetFile>fooRules.xml</ruleSetFile> but it can only find it if put the entire path to fooRules.xml in there?!
Try eclipse-pmd (available in the Eclipse marketplace or via the update site http://www.acanda.ch/eclipse-pmd/release/latest). With eclipse-pmd you can configure your projects to use a single rule set file for several projects. It also stores its path relative to the workspace. You still have to configure each project individually though (for now, this will change in a future release).
To set up eclipse-pmd in the way you described you have to open the project properties of your first project, select the "PMD" property page and add the rule set. Select the rule set type "Workspace" and pick your rule set file.
For every other project you have to open the project's PMD property page where you'll find the previously selected rule set file which simply needs to be checked to activate.
If you set it up this way there will be a .eclipse-pmd file in each project containing the settings. If you check this into your version control system then no one else in your team has to set up anything (apart from installing eclipse-pmd).
Disclaimer: I wrote eclipse-pmd. Mostly because I had the exact same problems as you with the other plugin.
I've been struggling a long time to get this working with PMD for Eclipse. While Eclipse-PMD has this feature built-in, I had some other issues with it (e.g. I think it is not meant to create reports).
The trick was adding the rules to the project as a link.
Create the rule file, e.g. pmd.xml, in the parent folder of the project. Add the file to the projects to be checked, but add it as a reference. Therefore, drag the file from the explorer to the bundle and select:
In the project properties, in the PMD section, check Enable PMD and Apply and Close the settings.
Now close Eclipse. Edit the file with the name .pmd in the project folder by replacing the content with the following:
<?xml version="1.0" encoding="UTF-8"?>
<pmd>
<useProjectRuleSet>true</useProjectRuleSet>
<ruleSetFile>pmd.xml</ruleSetFile>
<includeDerivedFiles>false</includeDerivedFiles>
<violationsAsErrors>true</violationsAsErrors>
<fullBuildEnabled>true</fullBuildEnabled>
</pmd>
Restart Eclipse and right click the project. Select PMD/Check Code. Now, only the violations defined in pmd.xml should be reported.
Configuring PMD only using the GUI does not seem to work for me.

ADT20 and External JAR

I have tried absolutely everything to avoid the NoClassDefFoundError when trying to use an external jar. No dice. WTF ADT?!
From a clean, brand new project, add external jar to build path, put in libs folder, make sure it's checked. Android -> Fix Project Properties, adding and removing, rinsing and repeating. I checked the contents of the jar, and my files are there! I referenced it 20 ways, removed added and rebuilt, still the dern thing can't be found!!
Is there a way someone has, from step 1, made an external jar work inside Android using eclipse and ADT 20?
Edit 1
I tried adding it into only the libs/ folder, and tried what Ali suggested in this SO question. I think I'm going to have to just try and add the source to my project directly, but that seems plain silly.
Oh. My. Goodness.
Turns out, Android (still) does NOT support Java 7 and when I created my external project, it had the 1.7 (Java 7) as the default compliance level! Switching that down to match my Android project's compliance makes it all dandy.
Stuff like
List<MyClass> mList = new ArrayList<>();
And various #Override apparently made Android stick it's nose in the air.
Hopefully this helps someone else out who's been going bald over this issue!

How do I conditionally include or exclude a file from an archetype when project is generated?

I'm creating Maven 2 archetypes for our project (Weld). I would like to be able to control which files are placed into the generated project based on the value of a property that is defined during archetype:generate. For instance, I foresee the following prompt:
Define value for groupId: : com.example
Define value for artifactId: : myproject
Define value for package: com.example: :
Define value for includeGradleSupport: : y
Based on the value of includeGradleSupport, I want to include (or not include) the build.gradle file in the generated project. If the user does not want Gradle support, I don't want to clutter up the generated project with unnecessary files.
Another example is that I might need to provide a Jetty web fragment (to activate a listener perhaps) if the user wants Jetty support.
It's all about customization of the project based on what the developer intends to use. While I could create a whole other archetype, sometimes the changes are so slight that it would be easier to include/exclude a file.
Is there a way to control this behavior using the archetype-metadata.xml descriptor?
I personally would move the parts that can be removed/added on user request and put the into different maven profiles so u can build different part using different profiles
I can have a look into what coding it would take to enable this in the archetype plugin.
I think the primary vehicle to do this today would be to conditionally produce two different archetype artifacts during the original build. The archetype user would then explicitly use yourarchetype-withthing or yourarchetype-withoutthing.
I know this isn't perfectly what you are after and I agree that what you are asking for is a sensible use case.
While I could create a whole other archetype, sometimes the changes are so slight that it would be easier to include/exclude a file.
This sentence made me think...
It seems like you have a default project structure.
Let's suppose it is big, has many files. Of course, you don't want to duplicate the logic and the files in a different archetype.
Now sometimes, a project has an additional behavior (related to Gradle).
This sound a typical use-case for another archetype that does not start from nothing, but that comes after the first one. I've seen several examples of such archetypes on the web. The developper triggers this archetype only if the project needs Graddle. :-)
So I suggest : create your Graddle archetype, that adds only the files relevant to Graddle.
Thanks for the info Dan !
I just looked at looked at archetype plugin source code, and http://jira.codehaus.org/browse/ARCHETYPE-58 doesn't appear to have resolved this issue.
Just created http://jira.codehaus.org/browse/ARCHETYPE-424 to track it.

Categories