Cannot create new activity in android studio - android

I keep getting an IllegalStateException error in the event log while creating new activity in android studio:
11:27:15 InvalidReferenceException: Error executing FreeMarker template: The following has evaluated to null or missing:
==> srcDir [in template "root://activities/common/common_globals.xml.ftl" at line 41, column 34]
Tip: If the failing expression is known to be legally null/missing, either specify a default value with myOptionalVar!myDefault, or use when-presentwhen-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthessis: (myOptionVar.foo)!myDefault, (myOptionVar.foo)??

I've encountered the same problem and trying the following steps were working for me:
close android studio
delete folders:
.idea and
.gradle
re-open project using android studio

Method 1:Just Remove the following code from your app level build.gradle
debug {
storeFile file('/Users/Razz/Documents/keys/keystore.jks')
storePassword 'ABC#123'
keyAlias 'key0'
keyPassword 'ABC#123'
}
Method 2: In case, if there are two packages together (kotlin and java)
I was facing the same problem as whenever I create new activity form the activity templates provided by the android studio. Nothing was happening even after Gradle sync completes successfull.
After a long item, I figure out that, java directory name inside my project changed into kotlin somehow. And I supposed Android Studio looking for the java package to create new Activity.
Then, to solve this issue, I follow the below steps:
Closed Android Studio
Went to the project location up to java directory as ../ProjectName/app/src/main/
In this main directory, I had the kotlin directory instead of java.
So, I just renamed it to java.
Then opened the project with Android Studio, and that's all.
I created new activity it easily created one as it works before.

I have been faced that, after I setup my android environment.I already set up and configured everything, but this still occur.After searching a few mins, I found the problem in Logcat,
Then, I know project is missing Build Tool version. You have to give which build tool version you will use to run for project. Go to >> Project Structure , ( Cmd + ; ) in mac. Choose Compile Sdk Version and Build Tools Version,
After the gradle build, creating new activity from menu error has been fixed. I hope this will help for you.
Notes : Some of the projects from Github or bitbucket also missing Build Tools version when you cloned and run the project. These are the same errors and this approach can help to solve for them.

Comment the code in build.gradle which creates folders in tmp directory and then create the Activity.
After successful creation of activity ,revert back the commented code in build.gradle (Co)
allprojects {
/*String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("windows")) {
buildDir = "C:/tmp/${rootProject.name}/${project.name}"
}*/
repositories {
jcenter()
}
}

In the file build.gradle, add
buildDir = "C:/tmp/${rootProject.name}/${project.name}"
sychronize gradle then remove it and synchronize again. This worked for me.
allprojects {
buildDir = "C:/tmp/${rootProject.name}/${project.name}"
repositories {
jcenter()
}
}

I experienced to same issue 2 day ago and i solve it by update the below text. Check to gradle.build app and module to newer versions.
classpath 'com.google.gms:google-services:4.3.4'

I had the same issue.
Visit this Link.
https://code.google.com/p/android/issues/detail?id=232076
this happens if you have your project in a different drive other then C:
android studio will automatically create a copy of your project (i hope they are cache files) in the C: drive's tmp folder. this folder is the cause for this issue.
try File-> Invalidate Caches/Restart. or
just deleted the tmp folder in the c: drive and restart everything and it will work fine.

removing the build folder redirect code in the gradle file is a workaround.
allprojects {
//String osName = System.getProperty("os.name").toLowerCase();
//if (osName.contains("windows")) {
// buildDir = "C:/tmp/${rootProject.name}/${project.name}"
//}
repositories {
jcenter()
}
}
Found it here https://github.com/udacity/ud851-Exercises/issues/67

I have the same exact problem when trying to create a new activity.
IDE Fatal Errors
I was running Android Studio 3.2.1 on Windows 7 Professional. I did not have this problem until I started to switch loading project from different drives - I used to run my projects from F: drive and when I downloaded sample code to C: drive, creating new activities started to give this IDE fatal error.
Got a clue from online sources of a potential issue caused by buildDir path in build.gradle(Project:) shown below;
buildDir = "C:/tmp/${rootProject.name}/${project.name}"
Since my project working directory is in F: drive, I changed the above C: drive to F:
buildDir = "F:/tmp/${rootProject.name}/${project.name}"
With this simple change, I can now create new Activity.
If nothing else works for you I suggest you try this solution.

I had tried most of the above suggestions without any success; the directory was fine, invalidation of caches, etc. But if you right-click on the project folder, New > Activity > Gallery (all others are greyed-out), clicking on any activity template will show you the exact problem. In my case, for some reason, all of my Activities (including Basic and Empty) required minSdkVersion 16; not the original 15. I hope this works for you if others fail.

Related

Adding and debugging external project

I am developing an android app. I have added a new project to my gradle build as follows....
In the build.gradle I have added...
android {
dependencies {
implementation project(':code-scanner')
}
...
}
In the settings.gradle I have added...
include ":code-scanner"
project(':code-scanner').projectDir = new File(settingsDir , "../External/code-scanner")
The project builds fine. But I would like to be able to browse the source, and add breakpoints to the code-scanner project, but it does not show up in Android Studio.
I have tried importing module , but the folder is missing from the subsequent select folder dialog.
How can I add this code to android studio, and set breakpoints and debug....
Just in case. Based on Android Documentation dependencies should be defined outside android block. Maybe Gradle Build figures out your code, but your Android Studio can't find source code of your library.
What version of Android Studio are you using?
1- Make sure you put implementation project(':code-scanner') in app level build.gradle file
2- dependencies block should not be inside android block:
Not like this:
android {
dependencies {
implementation project(':code-scanner')
}
}
But like this:
android {
...
...
}
dependencies {
implementation project(':code-scanner')
}
I don't know which IDE you are using but most IDEs like Android Studio or IntelliJ look like the pictures below.
Or you can view your folder structure in Project view like this:
If you didn't accidentally delete it, it should be there.
The actual problem is the location of the project, which is outside of the root project directory:
include ":code-scanner"
// project(':code-scanner').projectDir = new File(settingsDir , "../External/code-scanner")
Better add it as a library module within the root project, then the code should be within IDE scope.
If you don't want to move the project into there, you could put a built artifact into the libs directory.
Adding a symbolic link might also work out (it's rather a file-system issue than a Gradle issue).
'code-scanner' project you have to add as a library to the current project,for that in code-scanner build.gradle file you have to add
apply plugin: 'com.android.library'
please check if it is missing.

jar not created even after including lint operations

I am trying to convert my Android app to JAR.
While clicking the build option in the GRADLE toolbar, it shows this error:
Fix the issues identified by lint or add the following to your build script to proceed with errors:
...
android {
lintOptions {
abortOnError false
}
}
Now I added these lines to my build.gradle but JAR has not been created and not showing any errors too. Pls help
try using the creteFullJarDebug or createFullJarRelease that are located in the other on the same tab
Apparently, there is a bug with fetching lintOptions. Maybe your problem is related to that. Try to change the order of repositories, move google() to the top in your project gradle and app gradle(if it exists) as well.

Unable to resolve dependency for ':app#debug/compileClasspath': Could not resolve

Newly installed Android studio 3.1.3 is giving strange dependencies error when making a new project and compiling for very first time.
A similar question that didn't help resolve the problem.
Event Logs:
Unable to resolve dependency for ':app#debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:28.0.0-alpha3.
Open File
Show Details
Unable to resolve dependency for ':app#debug/compileClasspath': Could not resolve com.android.support.constraint:constraint-layout:1.1.2.
Open File
Show Details
Unable to resolve dependency for ':app#debugAndroidTest/compileClasspath': Could not resolve com.android.support:appcompat-v7:28.0.0-alpha3.
Open File
Show Details
Unable to resolve dependency for ':app#debugAndroidTest/compileClasspath': Could not resolve com.android.support.constraint:constraint-layout:1.1.2.
Open File
Show Details
Unable to resolve dependency for ':app#debugUnitTest/compileClasspath': Could not resolve com.android.support:appcompat-v7:28.0.0-alpha3.
Open File
Show Details
Unable to resolve dependency for ':app#debugUnitTest/compileClasspath': Could not resolve com.android.support.constraint:constraint-layout:1.1.2.
Open File
Show Details
Unable to resolve dependency for ':app#release/compileClasspath': Could not resolve com.android.support:appcompat-v7:28.0.0-alpha3.
Open File
Show Details
Unable to resolve dependency for ':app#release/compileClasspath': Could not resolve com.android.support.constraint:constraint-layout:1.1.2.
Open File
Show Details
Unable to resolve dependency for ':app#releaseUnitTest/compileClasspath': Could not resolve com.android.support:appcompat-v7:28.0.0-alpha3.
Open File
Show Details
Unable to resolve dependency for ':app#releaseUnitTest/compileClasspath': Could not resolve com.android.support.constraint:constraint-layout:1.1.2.
Open File
Show Details
ScreenShot:
this problem happened to me several times and forcing https or http didn't resolve it either
You might be importing Application instead of Module. Well you can change it in module's gradle also.
Change
apply plugin: 'com.android.application'
to
apply plugin: 'com.android.library'
You also need to remove applicationId from the gradle.
I just figured out how to remove this gradle error, follow the following steps.
Go to "File".
Click on Invalidate Cache/ Restart.
Again click on Invalidate Cache / Restart(On dialoge window).
Let the gradle build without any interruption.
Thank You!
Regards, hope this will help.
I think the problems comes from the following:
The internet connection with u was unavailable so Android Studio asked you to enable the "offline work" and you just enabled it
To fix this:
File
Settings
Build, Execution, Deployment
Gradle
Uncheck offline work
why might unchecking the offline work solves the problem, because in the Gradle sometimes some dependencies need to update (the ones containing '+'), so internet connection is needed.
Try "File"->"Invalidate Caches / Restart ..."
Try to clean up your .gradle and .idea directory under your project root directory.
Try to add Google Maven repository and sync project
buildscript {
repositories {
jcenter()
google()
maven {
url "https://maven.google.com"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
}
}
allprojects {
repositories {
google()
jcenter()
maven {
url "https://maven.google.com"
}
}
}
If you are using Android Gradle Plugin 3.1.3, you should be sure that your gradle wrapper version is 4.4. Under the root directory of your project, find gradle-wrapper.properties and modify it as below.
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
I know its very late but I think it may help someone in resolving his issue.
In my case It was occurring because compileSdkVersion and targetSdkVersion was set to 29 while when I check my SDK Manager, It was showing that package is partially installed. Whereas SDK version 28 was completely installed. I changed my compileSdkVersion and targetSdkVersion to 28 along with support libraries.
Earlier:
compileSdkVersion 29
targetSdkVersion 29
implementation 'com.android.support:appcompat-v7:29.+'
implementation 'com.android.support:design:29.+'
After Modification:
compileSdkVersion 28
targetSdkVersion 28
implementation 'com.android.support:appcompat-v7:28.+'
implementation 'com.android.support:design:28.+'
It worked like a charm after applying these changes.
I had this issue with offline mode enable. I disabled offline mode and synced.
Open the Preferences, by clicking File > Settings.
In the left pane, click Build, Execution, Deployment > Gradle.
Uncheck the Offline work.
Apply changes and sync project again.
#shizhen answer not worked my case.
Spend more than one day and finally got a working solution.
I Was in office environment so by trying different methods my gradle file get corrupted.
So I removed all proxy and port info form from following file and things got worked.
User -> .gradle -> gradle.properties
Additionally I enabled "Auto-detect proxy settings" under Android studio -> preferences -> HTTP proxy for network and studio will auto detect network config.
Special credit
I'm just sharing this answer because I had similar problem.
In the end, error was caused because I inadvertently changed the fileTree. In my case, I fixed by changing:
// implementation or compile
implementation fileTree(include: ['*.jar'])
to
// implementation or compile
implementation fileTree(include: ['*.jar'], dir: 'libs')
As #Ebin Joy said, If your gradle file get corrupted then there is one simple solution for that. Manually give the proxy details like shown in image. then you're good to go. This solution only works if you using any closed networks like office network etc.
I have resolved this Gradle caching issue like below.
In case anyone using MacBook then below is the steps I used to resolve this issue.
There is a hidden Gradle folder. By using the below command we can open the hidden Gradle folder and remove the file called gradle.properties
shortcut (⌘ + shift + G) then enter this inside popup window ~/.gradle/ press enter
file to be removed -> gradle.properties
Then go back to the android studio and sync your project with Gradle files.
One possibility I have not seen mentioned. If the project you are importing uses android product flavors, you may have a mistake in your missingDimenstionStrategy.
In your :app build.gradle (the one code that is failing to resolve the dependency), ensure you have correctly set the specific flavor of the product that you are depending on. This allows all your later dependency code (e..g implementation, api, etc) to know which precise build it depends on
defaultConfig {
...<snip unrelated>...
// Ensure you specify the flavor you depend on!!
// If dep has multiple flavor dimensions, you need to specify them all
missingDimensionStrategy 'classpath', 'gms17'
}
FOR ANYONE GETTING THIS WHEN TRYING TO IMPORT THEIR OWN CREATED LIBRARIES
I have been playing with Kotlin Multiplatform libraries and was trying to publish my libraries using jitpack and then pulling them into other projects. I'm new to most of this and didn't know I needed to add publishLibraryVariants to my android configuration in gradle. I followed other tutorials that didn't require this, so I'm not sure what it is about Kotlin MPP that makes you need it. This is the code though. You could likely publish other variants that met your needs, but these appear to be the standard requirements to build with a basic project. The () after android aren't absolutely necessary, but the default script comes with them so I left it. The code is essentially the same for Kotlin or Groovy DSL.
In the gradle script for the library being published
kotlin {
android() {
publishLibraryVariants("release", "debug")
…
}
…
}
Below solution may help to someone.
I faced this issue, when I use implementation project(':my_project_other_modules') in the new module.
I discussed with my teammates and I finally I got the solution from one of the person,
I have to use flavorDimensions & productFlavors. Because the app/build.gradle used flavorDimensions & productFlavors. When I add these in new module, the error didn't occur.
In my case, there was a typo in the code. Therefore beware to check that first before trying anything else.
I was unable to find the root cause of the issue but got a workaround. I started by setting my the java home variable as such.
vi ~/.bash_profile (this is for macs only. bash profiles are different on linux)
type the letter i for insert and then set the JAVA_HOME variable as such
export JAVA_HOME=/Applications/Android\Studio.app/Contents/jre/jdk/Contents/Home/
quit the vi editor with esc then type :wq
Restart the computer
Voila! Your android studio projects should build without any qualms
In my case :
When I setup AS, my windows was configured with proxy.
Later, I disconnect proxy and disable proxy in AS settings, But, in file
.gradle\gradle.properties - proxy - present
Just, in text editor clear proxy settings from this file
I had your issue, i fixed it . this error comes when your target api level is not completely downloaded . you have two ways: go to your SDK menu and download all of the android 9 components or the better way is go to your build.gradle(Module app) and change it like this:But remember, before applying these changes, make sure you have fully downloaded api lvl 8
In my case I used google play services...I increase library service it solved
implementation 'com.google.android.gms:play-services-auth:16.0.0'
Google play service must be same in library and app modules
Reference
Question still relevant as of Android Studio 3.5.2 for Windows.
In my specific use case, I was trying to add Gander (https://github.com/Ashok-Varma/Gander) to my list of dependencies when I keep getting this particular headache.
It turns out that I have yet to get JCenter Certificate approved in my cacerts file. I'm going through a company firewall and i had to do this with dependencies that I attempt to import. Thus, to do so:
Ensure that your Android Studio does not need to go through any
proxy.
Export the certificate where you get your dependency (usually
just JCenter)
Add the certificate to your cacerts file:
keytool -import -alias [your-certificate-name] -keystore 'C:\Program Files\Java\jdk[version]\jre\lib\security\cacerts' -file [absolute\path\to\your\certificate].cer
Restart Android Studio
Try syncing again.
Answer is based on this one: https://stackoverflow.com/a/26183328/4972380
If you have ever used a proxy, VPN, etc(or may not, I am not sure).....Then the solution below may help you...I don't know why (and if anybody can tell me why, I will appreciate that), but it works, pefectly. Have a try when you totally feel desperate about that issue.
Come to your project, and open gradle-wrapper.properties or gradle.properties, comment out these codes about proxy:
#systemProp.http.nonProxyHosts=118.89.144.241|47.112.105.125
#systemProp.http.proxyHost=127.0.0.1
#systemProp.http.proxyPort=1081
#systemProp.https.nonProxyHosts=118.89.144.241|47.112.105.125
#systemProp.https.proxyHost=127.0.0.1
#systemProp.https.proxyPort=1081
Then, it might work.
PS: I met this problem when I try to use dataBinding library, and when I added the code
buildFeatures {
dataBinding true
}
into gradle as the guide told me and Syns the project, I got such an error:"Unable to resolve dependency for ':app#debug/compileClasspath': Could not resolve ......". Finally I did what I described above, and I successed. What I experience may give you a hint, so I post the solution here and hope it might help.
Try to add type of configuration in dependency line. For example:
implementation project(path: ':some_module', **configuration: 'default'**)`
People answering about offline work is active is right. But it was located in different place in my case. To find it in the top bar menu select
View/Tool Windows/ Graddle
Toogle the offline button if active. It is a small rectangle with two centered slashes
In adittion you can clic the help menu in the top bar menu and write "gradle" and it suggest the locations.
It's neither a cache problem nor an application versus library issue. This is a certificate problem. If you try to run your project instead of gradle build, you'll see it struggles to download certificates. To solve this issue, just add the certificates that google changes each other month.
Here is my command line, please edit it accordingly with your own paths. The password to keystore is changeit.
keytool -import -alias google_10 -keystore /Library/Java/JavaVirtualMachines/adoptopenjdk-9.jdk/Contents/Home/lib/security/cacerts -file ~/Desktop/GTS\ CA\ 1C3.cer

Android Studio: Snapshot Dependencies Don't Update properly

I'm working With Android Studio 8.9
I've got a build.gradle with the following dependency defined:
compile ('my.program.commons:my-program-commons:0.0.2-SNAPSHOT#jar')
This dependency is stored in a private Sonatype nexus repository.
When I make changes in the my.program.commons code, I upload to nexus.
The problem is that when I then try to compile against the new SNAPSHOT android studio will fail to pick up changes.
When run from the command line gradle will build succesfully - but Android Studio will not recognize the new files.
If i do a version tick - say from 0.0.2-SNAPSHOT to 0.0.3-SNAPSHOT Android Studio will understand the new version and download and everything works out fine.
I don't want to have to do a minor version tick on every single change.
In my case, use changing = true not work for me. But configure cache changing modules solve my problem. Sample code below, add in build.gradle file:
configurations.all {
// Don't cache changing modules at all.
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
See: https://docs.gradle.org/current/userguide/dependency_management.html
You can also put a flag called "changing" that will trigger Gradle to always pull the latest, for example:
compile ('my.program.commons:my-program-commons:0.0.2-SNAPSHOT#jar') {
changing = true;
}
You need to configure the cache duration, by default gradle won't look for updates for 24 hours:
http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:controlling_caching
In my case, removing the whole <project_root>/.idea/libraries directory, was the only solution that worked. AndroidStudio stores some cached dependencies configurations there. Removing the directory makes it refetch all of them one more time.
You can write some script/task that will automate this removal and run it as part of the Gradle clean task.

Cannot resolve R.java, duplicate class

I just start using Android Studio for a week and it works great for me, but when I started Android Studio today I get the error: 'error: duplicate class: mypackage.R'. I saw this error before when I used Eclipse so I tried to rebuild the project a few times and restarting Android Studio, this didn't help.
After reading some Stackoverflow questions I tried to deleted R.java and rebuild again, now I don't get any error while rebuilding. The only problem is that Android Studio cannot resolve R, so every line which uses R gets an error (project builds and run).
I also tried to delete all the R.class files but this doesn't help either. I checked if some class imports android.R, but they all don't, they just import 'mypackage.R'. I even deleted all my files and checked out a older version of my project but I still have the same problem.
Edit:
If I don't delete R.java the compiler doesn't give any error. Just when I try to build I get a lot of errors like: 'error: cannot find symbol variable button_login'. If I search the R.java file for 'button_login' I just find it. I did this with multiple errors.
Edit2:
When I deleted all the libaries the project now builds. But the problem is that I need those libaries (HTTPComponents). I added them from maven (File --> Project Structure --> Libaries --> +-sign') and added them to my settings.graddle:
buildscript {
repositories {
maven { url 'http://repo1.maven.org/maven2' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4'
}
}
apply plugin: 'android'
dependencies {
compile files('libs/android-support-v4.jar')
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.2.5'
compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.2.5'
//compile 'org.apache.httpcomponents-httpclient:4.2.5' doesn't work either
//compile 'org.apache.httpcomponents-httpmime:4.2.5' doesn't work either
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 15
targetSdkVersion 16
}
}
When I run gradlew.bat --stacktrace --info assemble I get errors that Gradle is unable to find the libaries from the maven repository. I checked the repository but they are available. http://search.maven.org/#browse%7C1628757896
Unfortunately I run into this as well, sometimes frequently, mostly happens when I put my computer to sleep and back on while Eclipse is on. Sometimes recompiling and validating the project works.
I did find this solution online somewhere, lost the link and do not claim credits for this:
Disable auto build, and clean the project then
Right click your project -> properties -> Java Build Path -> Source -> Add Folder -> add gen and src
Then compile
If that doesn't work, try to delete the gen folder and do that process
Let me know.
Delete the Build folder generated by Android Studio automatically!
Problem is simple usually. You have fresh instal of studio? So you just fogot add SDK support for those version Android in wich try to compile project. Android Studio can`t generate R file. Start SDK manager, install all missing SDK version and rebuld project.
Another problem can be if you use 64bit OS. You ned to install 32 bit lib, because aapt can`t work with 64bit libs.
in Ubuntu install ia32-libs
Fedora described here
in other distr find libs in google (just google:ia32-libs for "mydistr"), i cant describe all of them ;)
P.S. sorry for my English ;)
Delete all class file in your_package_name(androisTest) folder only keep ApplicationTest file.
If you are using some library from which you are getting this error, just delete the build folder under your app source and rebuild the project. I was using OpenCV library for which I w as getting this error and that got resolved by deleting the build folder and rebuilding the project.
Delete all generated code inside "gen" folder.
Uncheck Project->Build Automatically in eclipse.
compile android source once again.
Error will be removed, worked for me.
This still happens sometimes in Android Studio, but a simple Build / Clean Project followed by a Build / Rebuild Project takes care of it.
I have not had this problem for a long time until today.
Error:(10, 14) java: duplicate class: com.domain.name.R
After 2 hours of wasting time on the project and getting this error,
Finally I removed the .idea, gen and out folders and also iml file.
Then I closed the project and then re-import it using import project of main menu again.
Its working well right now.

Categories

Resources