How do I add Guava to my Android Studio project? - android

First and foremost, I am aware of the existence of this question - How do I add a library project to Android Studio? - and unfortunately, it has not helped me.
My goal is rather simple. I want to write an Android app using the Android Studio IDE (0.2.11), and the Guava libraries in my code.
I do not know Gradle, I've only started using Android Studio and my Visual Studio/C# background has dumbed me down, for which I apologize (in that Mickey Mouse world, you typically just add a library reference and off you go).
I will document my steps with screenshots. I mostly followed advice given in this answer.
I created a libraries folder under my project folder.
I cloned Guava repository into it.
Files successfully appeared.
I went to Project Structure and selected Import Module.
I selected Create module from existing sources and agreed to all the default choices.
I updated my settings.gradle file to include ':libraries:guava', ':Test':
And my build.gradle file with compile project(":libraries:guava"):
But all I'm getting whenever I'm trying to rebuild the project is:
Error: Gradle: A problem occurred configuring project ':Test'.
> Failed to notify project evaluation listener.
> Configuration with name 'default' not found.
I did try putting a build.gradle as below in the guava folder:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android-library'
dependencies {
compile 'com.android.support:support-v4:13.0.+'
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}
(as the aforementioned answer says).
I have googled up and down to find the "correct" build.gradle for Guava.
https://code.google.com/p/guava-libraries/wiki/UseGuavaInYourBuild - didn't help me, either.
I did try countless things which I will not describe here as they were rather haphazard - I tried adding a module dependency, I tried turning Use auto-import on in Gradle settings, etc.
I know it's not a way of solving issues and I promise I will diligently read Gradle's User Guide from 1 through 5.4.2 to 7.3, but I can't believe this is really prerequisite to achieve something as unremarkable as merely adding a library to a project? Why is there no default build.gradle file from which one could start to fiddle with all sorts of things if necessary?
And the real question - how do I create an app (in Android Studio) that builds, actually runs on an Android device and on the top of that allows me to use Guava so I could sort a map by values without writing 50 lines of code? :)
Sorry about the chatty tone of my question, I know the drill around here, it's just my way of venting my frustration off.
Judging by how many votes were casted for questions and answers that tackled similar issues, I'm sure I'm not the only one who would benefit from some more instructions. I would start a bounty on it straight away, but the rules forbid me.

If you just need to use a stable, released version of the Guava libraries, importing it is extremely easy.
Just go to the build.gradlefile of the module where you want to use the library (i.e GuavaTestProject/GuavaTest/build.gradle) and, right after
repositories {
mavenCentral()
}
add a Maven dependency:
dependencies {
compile group: 'com.google.guava', name: 'guava', version: '15.0'
}
Rebuild your project if needed and that's all (tested right now with a fresh project created with Android Studio 0.2.13).
If you really need to include the source code of the Guava library and compile it yourself as a module of your Gradle build that's an entirely different problem because Guava is build with Maven and so you need to move the Guava build system from Maven to Gradle, which I think is overwhelmingly complex for your goals.
If you just need to browse the source or view it while debugging, what I would do is:
Download Guava source code on a separate folder:
git clone https://code.google.com/p/guava-libraries/
git checkout v15.0
When Android Studio doesn't find the sources, click on "Attach sources" and point to this alternative location.
I think if you don't need to actually modify and compile Guava source code this is the easiest solution.

dependencies {
compile 'com.google.guava:guava:19.0'
}
Source: https://github.com/google/guava
EDIT:
As of v22, there's specific guava version for Android.
dependencies {
compile 'com.google.guava:guava:22.0-android'
}
* Thanks Sam :)

Thats a lot of info in your question.
I am using Guava too. But I don't remember going through any of this trouble..
Guava is available on the mavencentral. So adding guava to your project should be fairly simple. AFAIK, you do not need to checkout, build and add a project dependency etc..
See gradle file for my app below.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
// Dependencies
dependencies {
compile fileTree(dir: 'libs', include: '*.jar') // jar files under the libs folder.
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0#aar' // actionbarsherlock,
compile 'com.android.support:support-v4:18.0.0' // android support lib
compile 'com.google.code.gson:gson:2.2.4' // google GSON
compile 'com.google.guava:guava:14.0.1' // guava 14.0.1
}

do not use the full guava library, use the version specific for android,
dependencies {
compile 'com.google.guava:guava:23.0-android'
}

In Android Studio 0.3.0 This is now working as it should on Mac. See the release notes for additional options in adding libraries
http://tools.android.com/recent/androidstudio030released
I have been working on Windows now and there are two options
Right click on a jar in libs and you have an add to library
Or you can push F4 and get to open library settings so it seems you do not have to struggle as much on Windows as on a Mac
This is what I did. Please read to the end since it works inconsistently and if you do not see the blue arrow first try there is a resolution. First I created a libs folder. I do not think this is needed though but it is a habit.
First try go to File , Project Structure.
If you see a little blue arrow at the top left push it and you will go to the screen where you can add a library
If you manage to get to this screen below push the plus sign and add the library.
You may also see a red line at the bottom saying Guava not used with a light bulb. This fill add the dependancy to the Gradle Build File
IF YOU DONT SEE THE BLUE ARROW
GO instead to File, Other settings, Default project structure.
From that screen you can add the library
Then go back to project structure and add it. The thing is that it will remain as a default for all your projects so you can add and remove it for each individual project via the project structure menu. I am not sure if this is a bug in Android Studio the fact that you can be blocked from adding it to the individual project without changing the default.

For Android Studio 3.2.1:
Click the File/Project Structure menu (ctrl+alt+shift+S). Press the + button in the Dependencies tab from the app menu to add a Library dependency.
Look for com.google.guava:guava:(whatever number is the most recent one) and add it.

Related

Android Studio Gradle dependency doesn't show up in External Libraries

I'm using Android Studio 3.0.1 and I'm trying to add an online dependency and while Gradle initially syncs without a problem it doesn't show my dependency in External Libraries and my code that references the dependency doesn't work.
Here's a snippet of what my build.gradle file looks like:
repositories {
mavenCentral()
maven { url 'https://oss.sonatype.org/content/groups/public/' }
}
dependencies {
compile group: 'com.fortysevendeg.android', name: 'swipelistview', version: '1.0-SNAPSHOT'
}
I'm pretty new to android development (took over an existing project from a dev who quit without leaving any documentation) so I'm not sure if this is a mistake with how to add a project dependency or if there is a problem with the dependency that I'm trying to add. Any help would be greatly appreciated!
I was able to get this to work by changing the dependency declaration to:
compile group: 'com.fortysevendeg.android', name: 'swipelistview', version: '1.0-SNAPSHOT', classifier: 'jar-with-dependencies'
The library artifacts up on the repository include an apklib and a JAR with a special classifier. The apklib format is not supported by Android Studio, and unfortunately the classifier on the JAR means that it's not accessible simply using the group-name-version format when declaring dependencies.
Your build.gradle file seems fine. If you want to keep the library specified as an external library, you can try and define the dependency using the alternative notation, replace:
compile group: 'com.fortysevendeg.android', name: 'swipelistview', version: '1.0-SNAPSHOT'
with:
compile 'com.fortysevendeg.android:swipelistview:1.0-SNAPSHOT'
The alternative approach is to download the jar file yourself and use it as a local dependency. If you navigate to the maven repository you can inspect the package which is included as a dependency and download the jar directly. Place the jar file in the libs folder of your project and add the following to your build.gradle file:
compile fileTree(dir: 'libs', include: ['*.jar'])
For further details on how to configure the dependencies of your gradle project, check out the Android Studio documentation here.
Based on the information you have provided, this should fix your issues. If this does not solve the error then there may be other issues with the project.
Your dependencies should not placed in the top-level build.gradle file where the repositories are defined. There is even a comment in that file that says so, by default.
You app dependencies should be the module's build.gradle along with the others like android-support
Additionally, that library is very old, and is a SNAPSHOT build, meaning it isn't meant to be generally used in a release environment. You should find an alternative... And there are plenty of other ListView swiping ones

Fragmentation in Android Studio version on include aar external Dependency

Many of the Android App Dev almost shifted to Android Studio which makes Dev life much more easier but few features works fine in one version will not work on another version but in next version it will work fine !
I'm talking about including aar external Dependency
See this comments:
Ref: SO
There are different ways to import an arr file but we need to tryout all methods find the solution for the version you are using !
I Found easy working solution for Android Studio 1.1.0 (not sure It works on other versions)
Simply add new module--> select AAR/JAR type
select the required .arr file, give the name or folder otherwise it will select same file name to folder name!
In above image shows if you shift from Android mode to project mode you can observe new lib module added which contains arr file!
and finally add compile project(':ndlib') to app gradle
Solutions that not worked:
allprojects {
repositories {
jcenter()
flatDir {
dirs 'aar'
}
}
dependencies {
compile(name:'myLibrary', ext:'aar')
}

How to add testCompile dependencies to IDE classpath

I have been struggling with unit-test-android problem for quite a long time. I have seen this, this and that, finally I found the gradle-android-test-plugin and even got it working. I can now run the tests with gradlew test command.
But, writing those tests in IDE (Android Studio or IntelliJ 13) is far from comfortable, because it does not see the junit & Robolectric dependencies added with testCompile dependency.
Is there any way to add these dependencies to the IDE classpath but still avoid to package them in the production app (thus, AFAIU compile dependency cannot be used)?
I had the same problem with IntelliJ 14.1.3 today. The solution was to run the steps outlined here. Basically:
Add JUnit and other dependencies via testCompile 'junit:junit:4.+', etz
Put test sources in src/test/java/...
To make the IDE find the test-dependencies (gradle will find them fine), open the "Build Variants"-view and set "Test Artifact" to "Unit Test". In "Project Structure", the testing dependencies should show up in your module with the "Test"-scope
The commandline to run a test is testXxx, where Xxx is the build-type (debug/release/etz).
The important step here is the one in the "Build Variants" view. After you change it to "Unit Test", it will index and your libraries and full auto-completion are available.
For my Android test dependencies, I use instrumentTestCompile instead of testCompile. This works for me when running my tests in Android Studio. Hope this helps.
You can use the built-in idea plugin. That should set up test dependencies for you. You'll need to import the plugin:
apply plugin: 'idea'
Then run gradle idea, to generate module file (*.iml) and re-load your project. Note you'll have to be using non-directory based idea configuration for this to work.
In IntelliJ IDEA you need to configure couple things in your build.gradle
// add idea plugin
apply plugin: 'idea'
// make sure `configurations.testCompile` is added to idea.module
idea {
module {
scopes.TEST.plus += [ configurations.testCompile ]
}
}
For more info see:
http://www.gradle.org/docs/current/dsl/org.gradle.plugins.ide.idea.model.IdeaModule.html
Any dependency included with testCompile will be automatically imported into IDEA.

Android Studio Gradle Configuration with name 'default' not found

I am having problems compiling my app with Android Studio (0.1.5).
The app uses 2 libraries which I have included as follows:
settings.gradle
include ':myapp',':library',':android-ColorPickerPreference'
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4'
}
}
apply plugin: 'android'
dependencies {
compile files('libs/android-support-v4.jar')
compile project(':library')
compile project(':android-ColorPickerPreference')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 16
}
}
When compiling I get this message:
Gradle: A problem occurred configuring project ':myapp'.
> Failed to notify project evaluation listener.
> Configuration with name 'default' not found.
Could you help me with this message? Thanks!
In my case, after compiling with gradle tasks --info, the log was there :
Evaluating project ':libraries:VolleyLibrary' using empty build
file.
So it failed to find build.gradle file of the library.
Reason is the folder structure.
It was
-libraries
--volley
---VolleyLibrary
It is supposed to be
-libraries
--VolleyLibrary
I forgot to pull all submodules. So my
compile project(':something')
could not be resolved.
Solution
git submodule update --init
compile fileTree(dir: '//you libraries location//', include: ['android-ColorPickerPreference'])
Use above line in your app's gradle file instead of
compile project(':android-ColorPickerPreference')
Hope it helps
The following procedure solved my issue:
Go to your sub-project-module/library-module settings. (press F4 after selecting the module)
Right Click on Add > Android-Gradle.
Add build.gradle to your module.
Add the following script
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
apply plugin: 'android-library'
repositories {
mavenCentral()
}
android {
compileSdkVersion 18
buildToolsVersion "18.1.0"
defaultConfig {
minSdkVersion 10
targetSdkVersion 18
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}
add include ':yourModuleName' in your settings.gradle
I've also faced with this error - I forgot to create build.gradle script for library project.
Yet another cause - I was trying to include a module in settings.gradle using
include ':MyModule'
project(':MyModule').projectDir = new File(settingsDir, '../../MyModule')
Only problem was, I had just imported the module from Eclipse an forgot to move the directory outside my application project, i.e. the path '../../MyModule' didn't exist.
My solution is to simply remove a line from the settings.gradle file, which represents a module that doesn't exist:
include ':somesdk'
and also remove the corresponding line from the main project's build.gradle:
compile project(':somesdk')
I had a git submodule problem when getting this error. Try running gradle tasks --info for a more detailed problem description. I first used gradle tasks --debug, which was not nearly as helpful as --info.
Suppose you want to add a library (for example MyLib) to your project, You should follow these steps:
Prepare your library as a gradle Android library if your library's type is Eclipse ADT
For this job it's enough to import it in Android Studio
Copy your library folder, in this case MyLib folder, and paste it in your main project folder. It's a good practice to create a new folder in your main project folder and name it Libraries
Go to Android Studio and open Settings.gradle file, there you should include your library in your main project. For example include ':MyPrj', 'Libraries:MyLib'. Note: Current directory for this include statement is your main project folder. If you paste your project into a folder you must mention it's address relative to the main project directory. In my case I paste MyLib into Libraries folder. This Libraries name is not a keyword and you can choose other names for it
Open your Project Structure page(File->Project Structure...) click on modules then click on your main project go to dependencies tab click on + then choose Module dependency and there is your libraries and you can select them as you want
Hope it help
In my case I was using Gradle files that work under Windows but failed on Linux. The include ':SomeProject' and compile project(':SomeProject') were case sensitive and were not found.
For me folder was missing which was declared under settings.gradle.
Everything looks fine at first blush, but some poking around on here found an answer that could be helpful: https://stackoverflow.com/a/16905808/7944
Even the original answer writer doesn't sound super confident, but it's worth following up on. Also, you didn't say anything about your directory structure and so I'm assuming it's boring default stuff, but can't know for sure.
One other potential cause of this precise error: I found this error was resolved by commenting some unused libraries in build.gradle dependencies section. Make sure these paths and such are all correct.
I'd look real close at your compile project(':android-ColorPickerPreference') entry in the build.gradle - try commenting out the related code and this line in build.gradle and see if that compiles - then go from there resolving the path or library issue.
I had similar issue and found very simple way to add a library to the project.
Create folder "libs" in the root of your project.
Copy JAR file into that folder.
Go back to Android Studio, locate your JAR file and right click it, choose "Add As Library...", it will ask you only to which module you want to add it, well choose "app".
Now in your "app" module you can use classes from that JAR, it will be able to locate and add "import" declarations automatically and compile just okay. The only issue might be is that it adds dependency with absolute path like:
compile files('/home/user/proj/theproj/libs/thelib-1.2.3.jar')
in your "app/build.gradle".
Hope that helps!
I solved this issue by fixing some paths in settings.gradle as shown below:
include ':project-external-module'
project(':project-external-module').projectDir = file('/project/wrong/path')
I was including an external module to my project and had the wrong path for it.
I had this issue when I manually pasted google-play-services_lib into my project. Obviously, play-services didn't have a build.gradle file in it. The solution, I learned, is to put this dependency in my project's build.gradle (instead of hard-copying the play-services directory):
compile 'com.google.android.gms:play-services:4.0.+'
When i import my library manually i had same issue. I tried to add my library with file > import module and it solved my issue.
In my case I received this error when I misspelled the module name of the library (dependency) in build.gradle file.
So remember to check if the name of the module is correct.
build.gradle
dependencies {
compile project(':module-name-of-the-library')
}
I recently encountered this error when I refereneced a project that was initiliazed via a git submodule.
I ended up finding out that the root build.gradle file of the submodule (a java project) did not have the java plugin applied at the root level.
It only had
apply plugin: 'idea'
I added the java plugin:
apply plugin: 'idea'
apply plugin: 'java'
Once I applied the java plugin the 'default not found' message disappeared and the build succeeded.
Also... check if you have the module files inside your project.
For example, I have an app which uses the Volley module. During my studies on Android development, I accidentally removed the files which were inside the "volley" directory..
~/git/Sandbox/android/HelloWorld/volley $ ll
total 8
drwxrwxr-x 2 ivanleon ivanleon 4096 Jun 16 22:26 ./
drwxrwxr-x 6 ivanleon ivanleon 4096 Jun 17 01:51 ../
I just cloned the project (see bellow) and then, I made the Sync of the project at Android Studio (Tools > Android > Sync Project with Gradle Files), and Gradle build finished normally (Gradle Console: bottom right corner of Android Studio) ;).
~/git/Sandbox/android/HelloWorld/volley $ git clone https://android.googlesource.com/platform/frameworks/volley
Cloning into 'volley'...
remote: Counting objects: 164, done
remote: Finding sources: 100% (164/164)
remote: Total 3222 (delta 307), reused 3222 (delta 307)
Receiving objects: 100% (3222/3222), 1.22 MiB | 114.00 KiB/s, done.
Resolving deltas: 100% (307/307), done.
Checking connectivity... done.
~/git/Sandbox/android/AndroidGetJSON $ ls volley
Android.mk build build.xml pom.xml
proguard-project.txt src bintray.gradle build.gradle
custom_rules.xml proguard.cfg rules.gradle volley.iml
Your build.gradle for the module/library could be as simple as:
apply plugin: 'java'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
If your module is just a collection of .java POJO classes.
If it's model / entity classes and you're using annotations and have some dependencies you could add those in:
apply plugin: 'java'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
repositories {
mavenCentral()
}
dependencies {
compile 'com.j256.ormlite:ormlite-core:4.48'
compile 'com.j256.ormlite:ormlite-android:4.48'
compile 'com.j256.ormlite:ormlite-jdbc:4.48'
}
This happens when you are compiling imported or copied folder/project as module in libraries folder. This issue was raising when I did not include the build.gradle file. when I added the file all went just fine.
For me it turned out to be an relative symbolic link (to the referenced project) that couldn't be used by grade. (I was referencing a library). Thats a pretty edgy edge-case but maybe it helps someone in the future.
I solved it by putting a absolute symbolic link.
Before ln -s ../library after ln -s /the/full/path/to/the/library
I also faced the same issue and it resolved by changing one flag (gradle.ext.set("allowLocalEdits", true)) to false in settings.xml.
For me, one of dependent library does not exist in correct path, but the error message does not point THAT library correctly.
For example, what I missed is :library-3 but the error throws at :library-1.
poor gradle.
Try adding Volley library and sync and run the program. if one has pulled and i has volley usage and the error shows as -Android Studio Gradle Configuration with name 'default' not found then follow the step of adding the volley library in your gradle. hope it helps. I cleared my problem this way.

Proper way to add global library in android-studio/gradle

First of all, I know how to add a local library to the build.gradle file, it was discussed in several questions here already (which are all basically the same), see here, here and here. But you have to hardcode the paths in the compile files('/path/to/lib.jar') statements in the build.gradle file, which isn't nice, not redistributable, etc, IF you use a library not within the project's folder structure. I prefer to maintain this library for all my projects in the same place (so it is always up to date for all projects etc.). So I would like to know how to add a library, which is not available via Maven, to an Android-Studio project using gradle, in a sane way, given that the library is added as a global library in AS's preferences.
What I have done so far:
I use Google's new Android-Studio, which uses gradle for the build management, to build an Xposed framework module. For that, I have to include an external library, XposedLibrary, which I downloaded from the respective Github repository to keep it up-to-date.
It contains the jar XposedLibrary/XposedBridgeApi.jar, which I added in AS as a global library (Ctrl+Shift+Alt+S -> Global Libraries -> green plus to add the folder XposedLibrary). The compilation failed, complaining that it doesn't know the imported classes. So I had to manually add the library to the build.gradle file, adding the respective line in the dependencies like so:
dependencies {
compile files('libs/android-support-v4.jar')
compile files('/home/sebastian/dev/android/XposedMods/XposedLibrary/XposedBridgeApi.jar')
}
I tried out to just add compile files('XposedBridgeApi.jar') or compile files('XposedLibrary/XposedBridgeApi.jar') but this didn't work.
So, what is a nice way to add an AS global library to the dependencies without using full paths? (I don't like the idea of symlinking to the jar file from within the lib/ folder ;) )
when referencing a file via
files("relative/path/to/a.jar")
the relative path is evaluated relative to the buildscript this snippet is in. so when your build.gradle file is located in let's say '/a/project/build.gradle' then the jar should be in '/a/project/relative/path/to/a.jar'. In a multiproject gradle build you can put the the jar in a folder relative to the root - project and reference it in all subprojects via
rootProject.files("relative/to/root/a.jar")
hope that helps,
cheers,
René
This post describes how to get XposedBridgeApi.jar working with Gradle in Android Sudio: http://forum.xda-developers.com/showpost.php?p=41904291&postcount=1570
I think here is the proper way:
Import Xposed in Android Studio
Edit the /app/build.gradle like this:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
provided fileTree(dir: 'deps', include: ['*.jar'])
}
The best way is to use "provided files('src/XposedBridgeApi-54.jar')" as the lib isn't allowed to be included in the module, because the XposedBridge is already installed on the phone.
With Android Studio, you have to first understand that the IDE uses the same model for a project that your command line build (gradle) uses. That is why the Project Structure dialog has a pop up that says edits here will have no effect. So adding a global library will also have no effect.
The correct way to fix such issues is to edit your gradle build scripts so that the command line gradle build works properly. Then you should just have to click on "Tools | Android | Sync Project with Gradle files" menu item to refresh the project structure in the IDE.
Finally, if your dependencies are not going to be in Maven Central, then you'd have to create a local maven repository. Read the thread here: https://groups.google.com/d/msg/adt-dev/eCvbCCZwZjs/vGfg-4vNy9MJ for background.

Categories

Resources