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

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.

Related

How to download libraries in Android Studio?

Whenever I have to add certain library from the internet to my Android project, I add them inside the dependencies in the app level gradle script and it downloads the library for me. Is it possible to download these library files so that I can use them in other projects as well without downloading the whole library and dependency files again?
Just go to Maven central and download the libraries.
For example, here is Volley. Just click the download JAR button.
I would strongly recommend sticking with Gradle / Maven, though, to keep consistency with versions and appropriately handle additional dependencies for the libraries you want to download. They are called package managers for a reason, and they do their job well.
The libraries are actually downloaded to disk only once and shared between projects, they aren't downloaded for every new project.
Put library's jar file inside libs folder.
Add this line in module level build.gradle (if not present):
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Other libraries
}
Find the gradle dependency for your library and put it in dependencies of your build.gradle file. For Example,
dependencies {
// other dependencies
compile 'com.google.code.gson:gson:2.6.2'
}
and then build the gradle file.
I'd just run into an issue where a coworker's AS instance wasn't syncing with the server. In that case, we simply had to manually invoke the "Sync Project with Gradle File". For whatever reason, his AS instance wasn't doing that automatically.

The best way to integrate third party library in Android studio

We can find some very good open source libraries for android. I want to know what is the best way to integrate them to our own projects in Android studio. Here are some basic methods:
Copy the source code and resource files into our own project. We need to change a lot of codes (the package name, and the name in xml,etc)
If jar files is provided, I just create libs folder for my project and copy the jar files inside. And add the jar file in Module setting's dependencies. But unfortunately I got a lot of error messages like "Gradle: Package com.google.gson doesn't exist".
Is there a general rule to add third party source or jar files into an existing android studio project? Thanks
I prefer to use central repository for dependencies management. So for gson 2.3 dependency you should add to build.gradle file:
Specify that you want to use maven central repository for your dependency
repositories {jcenter()}
Add compile dependency to gson 2.6.2
dependencies {compile 'com.google.code.gson:gson:2.6.2'}
Android Studio as well as your CI server should easily build your project now. And you can continue app development.
I prefer to use central repository for dependencies management because:
easier scope management - some libraries are only for testing, some should be included to apk and some are part of running environment (like android.jar itself)
easier transitive dependencies management - it is quite hard to collect libraries dependencies and if you use "jar-with-dependencies" you could get error "class already added" during dexing
lighter repository and easier dependency upgrade
Examples:
Robolectric jar should be used for unit testing only and shouldn't be part of apk itself
Repository is clean from different folders with jars, checkout takes much less. No needs to download and replace old jars with new jars
I should notice:
Not many libraries are in maven central and you should make some effort to use them such way in your project
You could much easier get to "class already added" error during dexing with central repository approach
You can mix usage of dependencies from central repository and from lib folder, but I prefer to use only one way for simplicity
Put the Gson jar (in my case, gson-2.2.4.jar) into the libs folder
Right click it and hit 'Add as library'
Ensure that compile files('libs/gson-2.2.4.jar') is in your build.gradle file
Do a clean build (you can probably do this fine in Android Studio, but to make sure I navigated in a terminal to the root folder of my app and typed gradlew clean. I'm on Mac OS X, the command might be different on your system
This series of steps was taken from Android Studio: Add jar as library? and is not my original answer. I am posting them here, again, because your question was the third in search results on Google when looking up this same topic. Hence, copying.
All credits to the one who wrote the steps.
Download & Copy Your .jar file in libs folder then adding one line to build.gradle:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar']) ----> AS creates this
compile 'com.google.code.gson:gson:2.3.4' ----------> I added this one
}
Do not forget to click "Sync now"
I´m using Android Studio 1.1.0
Download and copy your jar to libs folder then add the following to your app.gradle file and SYNC.
dependencies {
compile 'com.google.code.gson:gson:{version_you_need}'
}
repositories{
flatDir{
dirs 'libs'
}
}

Library projects in Android Studio only work if nested in the project tree?

I'm trying to build a project dependent on ActionbarSherlock in Android Studio.
After much reading I've ended up having a working build, but only if I nest the ABS project inside my main project like so:
MainProject
MainProject\ABS (copied here and then used import module)
MainProject\MainModule (the one created by the wizard)
I had to edit the various Gradle files, settings.gradle is as follows:
include ':OnTop'
include ':ActionbarSherlock'
I fixed the dependencies in the build.gradle files accordingly.
This is suboptimal, I think. Surely I don't want to replicate the ABS module in every new project that uses it? What should I be doing instead?
Every step are here : How do I add a library project to Android Studio?
If you want to more about gradle see the Google I/O conference by Xavier Ducrohet on youtube : http://www.youtube.com/watch?v=LCJAgPkpmR0
I searched this issue enough and finally these are my results:-
This sample project
-> project root
d:\asprojects\thisproject
-> module
d:\asprojects\thisproject\MyModule
-> libraries
d:\asprojects\lvl
d:\asprojects\MyLibrary
-> jars
D:/asprojects/android-support-v4.jar
D:/asprojects/GoogleAdMobAdsSdk-6.4.1.jar
-If you want to use external (outside the project) libraries then the settings.gradle has to point to it like so:-
settings.gradle
include ':lvl', ':MyLibrary', ':MyModule'
project(':MyLibrary').projectDir = new File('D:/asprojects/MyLibrary')
project(':lvl').projectDir = new File('D:/asprojects/lvl')
-Then you need to setup the build.gradle for the MyModule correctly like so:-
build.gradle
dependencies
{
compile files('D:/asprojects/android-support-v4.jar')
compile files('D:/asprojects/GoogleAdMobAdsSdk-6.4.1.jar')
compile project(':lvl') compile project(':MyLibrary')
}
-But the IDE will not like these absolute paths and will say not found.
-But gradlw from commandline work justs fine:-
gradlew clean
gradlew build
gradlew installRelease
etc

How to import relative project with the Android Studio(not jar) [duplicate]

How do I add a library project (such as Sherlock ABS) to Android Studio?
(Not to the old ADT Eclipse-based bundle, but to the new Android Studio.)
Update for Android Studio 1.0
Since Android Studio 1.0 was released (and a lot of versions between v1.0 and one of the firsts from the time of my previous answer) some things has changed.
My description is focused on adding external library project by hand via Gradle files (for better understanding the process). If you want to add a library via Android Studio creator just check the answer below with visual guide (there are some differences between Android Studio 1.0 and those from screenshots, but the process is very similar).
Before you start adding a library to your project by hand, consider adding the external dependency. It won’t mess in your project structure. Almost every well-known Android library is available in a Maven repository and its installation takes only one line of code in the app/build.gradle file:
dependencies {
implementation 'com.jakewharton:butterknife:6.0.0'
}
Adding the library
Here is the full process of adding external Android library to our project:
Create a new project via Android Studio creator. I named it HelloWorld.
Here is the original project structure created by Android Studio:
HelloWorld/
app/
- build.gradle // local Gradle configuration (for app only)
...
- build.gradle // Global Gradle configuration (for whole project)
- settings.gradle
- gradle.properties
...
In the root directory (HelloWorld/), create new folder: /libs in which we’ll place our external libraries (this step is not required - only for keeping a cleaner project structure).
Paste your library in the newly created /libs folder. In this example I used PagerSlidingTabStrip library (just download ZIP from GitHub, rename library directory to „PagerSlidingTabStrip" and copy it). Here is the new structure of our project:
HelloWorld/
app/
- build.gradle // Local Gradle configuration (for app only)
...
libs/
PagerSlidingTabStrip/
- build.gradle // Local Gradle configuration (for library only)
- build.gradle // Global Gradle configuration (for whole project)
- settings.gradle
- gradle.properties
...
Edit settings.gradle by adding your library to include. If you use a custom path like I did, you have also to define the project directory for our library. A whole settings.gradle should look like below:
include ':app', ':PagerSlidingTabStrip'
project(':PagerSlidingTabStrip').projectDir = new File('libs/PagerSlidingTabStrip')
5.1 If you face "Default Configuration" error, then try this instead of step 5,
include ':app'
include ':libs:PagerSlidingTabStrip'
In app/build.gradle add our library project as an dependency:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:21.0.3'
implementation project(":PagerSlidingTabStrip")
}
6.1. If you followed step 5.1, then follow this instead of 6,
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:21.0.3'
implementation project(":libs:PagerSlidingTabStrip")
}
If your library project doesn’t have build.gradle file you have to create it manually. Here is example of that file:
apply plugin: 'com.android.library'
dependencies {
implementation 'com.android.support:support-v4:21.0.3'
}
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
minSdkVersion 14
targetSdkVersion 21
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
}
}
}
Additionally you can create a global configuration for your project which will contain SDK versions and build tools version for every module to keep consistency. Just edit gradle.properties file and add lines:
ANDROID_BUILD_MIN_SDK_VERSION=14
ANDROID_BUILD_TARGET_SDK_VERSION=21
ANDROID_BUILD_TOOLS_VERSION=21.1.3
ANDROID_BUILD_SDK_VERSION=21
Now you can use it in your build.gradle files (in app and libraries modules) like below:
//...
android {
compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
defaultConfig {
minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
}
}
//...
That’s all. Just click‚ synchronise the project with the Gradle’ icon . Your library should be available in your project.
Google I/O 2013 - The New Android SDK Build System is a great presentation about building Android apps with Gradle Build System: As Xavier Ducrohet said:
Android Studio is all about editing, and debugging and profiling.
It's not about building any more.
At the beginning it may be little bit confusing (especially for those, who works with Eclipse and have never seen the ant - like me ;) ), but at the end Gradle gives us some great opportunities and it worth to learn this build system.
Here is the visual guide:
Update for Android Studio 0.8.2:
In Android Studio 0.8.2, go to Project Structure -> under Modules just hit the plus button and select Import Existing Project and import actionbarsherlock. Then synchronise your Gradle files.
If you face the error
Error: The SDK Build Tools revision (xx.x.x) is too low. Minimum
required is yy.y.y
just open the build.gradle file in actionbarsherlock directory and update the buildToolsVersion to the suggested one.
android {
compileSdkVersion 19
buildToolsVersion 'yy.y.y'
Menu File -> Project Structure...:
Module -> Import Module
After importing the library module, select your project module and add the dependency:
And then select the imported module:
Use menu File -> Project Structure -> Modules.
I started using it today. It is a bit different.
For Sherlock, maybe you want to delete their test directory, or add the junit.jar file to the classpath.
To import the library using gradle, you can have to add it to the dependencies section of your build.gradle (the module's one).
E.g.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.0'
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0#aar'
}
Android Studio is changing.
There exist a section named "Open module settings" if you
right-click on a module folder in the project section of Android
Studio (I'm using the version 0.2.10).
I would consider Dependencies, Android Libraries and Multi-project setup necessary reading. Please take a few minutes to do so.
Particularly, in the case of a non-jar library project, read the following snippet from above source:
Gradle projects can also depend on other gradle projects by using a multi-project setup.
A multi-project setup usually works by having all the projects as sub folders of a given root project.
For instance, given to following structure:
MyProject/
+ app/
+ libraries/
+ lib1/
+ lib2/
We can identify 3 projects. Gradle will reference them with the following name:
:app
:libraries:lib1
:libraries:lib2
Each projects will have its own build.gradle declaring how it gets built.
Additionally, there will be a file called settings.gradle at the root declaring the projects.
This gives the following structure:
MyProject/
| settings.gradle
+ app/
| build.gradle
+ libraries/
+ lib1/
| build.gradle
+ lib2/
| build.gradle
The content of settings.gradle is very simple:
include ':app', ':libraries:lib1', ':libraries:lib2'
This defines which folder is actually a Gradle project.
The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies:
dependencies {
compile project(':libraries:lib1')
}
Kindly note that there was little or no use of Android Studio GUI to make this happen.
I am currently using git submodules to link the nested library to the actual library git repo to avoid a dependency mess.
I have just found an easier way (rather than writing directly into the .gradle files).
This is for Android Studio 1.1.0.
Menu File -> New Module...:
Click on "Import Existing Project".
Select the desired library and the desired module.
Click finish.
Android Studio will import the library into your project. It will sync gradle files.
Add the imported module to your project's dependencies.
Right click on the app folder -> Open Module settings -> go to the dependencies tab -> Click on the '+' button -> click on Module Dependency.
The library module will be then added to the project's dependencies.
???
Profit
The easiest way I found to include external library project is (for example to include a Facebook library which is stored one directory up in the dependencies folder):
In settings.gradle add
include ':facebook'
project(':facebook').projectDir = new File(settingsDir, '../dependencies/FacebookSDK')
In build.gradle dependencies section, add
compile project ('facebook')
All left to do is synchronise the project with gradle files.
A simple way to add a JAR file as a library to your Android Studio project:
a) Copy your *.jar files
b) Paste into the libs directory under your projects:
c) Add to build.gradle:
dependencies {
...
compile files('libs/ScanAPIAndroid.jar', 'libs/ScanAPIFactoryAndroid.jar', .., ..)
}
b) If your project from example com.example.MYProject and libraries com.example.ScanAPI has the same namespace com.example, Android Studio will check your build and create all necessary changes in your project. After that you can review these settings in menu File -> Project Structure.
c) If your project and libraries have a different namespace you have to right click on the library and select option "Add as Library" and select the type what you need.
Remember the "Project structure" option is not doing any auto changes in "build.gradle" in the current version of Android Studio (0.2.3). Maybe this feature will be available in the next versions.
Option 1: Drop Files Into Project's libs/directory
The relevant build.gradle file will then update automatically.
Option 2: Modify build.gradle File Manually
Open your build.gradle file and add a new build rule to the dependencies closure. For example, if you wanted to add Google Play Services, your project's dependencies section would look something like this:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.gms:play-services:6.5.+'
}
Option 3: Use Android Studio's User Interface
In the Project panel, Control + click the module you want to add the dependency to and select Open Module Settings.
Select the Dependencies tab, followed by the + button in the bottom-left corner. You can choose from the following list of options:
Library Dependency
File Dependency
Module Dependency
You can then enter more information about the dependency you want to add to your project. For example, if you choose Library Dependency, Android Studio displays a list of libraries for you to choose from.
Once you've added your dependency, check your module-level build.gradle file. It should have automatically updated to include the new dependency.
Source
You can do this easily. Go to menu File -> New -> Import Module...:
Browse for the directory which contains the module. Click Finish:
Go to Project Structure and add Module Dependency:
Note: If you receive an SDK error, update that one.
This is how it works for me in Android Studio 1.5+
In the project where you want to add external library project,
go to menu File -> New -> *Import new Module**, navigate to the library project which you want to add to your project, select to add 'library' module in your project. You will get settings.gradle in your projects, beside app, included library, something like this:
include ':app', ':library'
Add in build.gradle(Module :app) in the dependencies section:
Compile project(':library')
Rebuild the project, and that's it.
*You can add as many libraries (modules) as you want. In that case in settings.gradle you will have:
include ':app', ':lib1', ':lib2', ...
And in build.gradle, you'll need to have:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Some other dependencies...
compile project(':lib1')
compile project(':lib2')
...
}
Press F4 to show Project Structure, click libraries or Global libraries, and click + to add the JAR file.
Click Modules what you want add jar, select the Dependencies tab, click +, and add Library.
If you need access to the resources of a library project (as you do with ABS) ensure that you add the library project/module as a "Module Dependency" instead of a "Library".
Editing library dependencies through the GUI is not advisable as that doesn't write those changes to your build.gradle file. So your project will not build from the command-line. We should edit the build.gradle file directly as follows.
For instance, given to following structure:
MyProject/
app/
libraries/
lib1/
lib2/
We can identify three projects. Gradle will reference them with the following names:
:app
:libraries:lib1
:libraries:lib2
The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies:
dependencies {
compile project(':libraries:lib1')
}
Android Studio 3.0
Just add the library name to the dependencies block of your app's build.gradle file.
dependencies {
// ...
implementation 'com.example:some-library:1.0.0'
}
Note that you should use implementation rather than compile now. This is new with Android Studio 3.0. See this Q&A for an explanation of the difference.
To add to the answer: If the IDE doesn't show any error, but when you try to compile, you get something like:
No resource found that matches the given name 'Theme.Sherlock.Light'
Your library project is probably compiled as an application project. To change this, go to:
Menu File -> Project structure -> Facets -> [Library name] -> Check "Library module".
First Way This is working for MacBook.
First select your builder.gradle file as given screen:
Add dependencies like as on the selected screen:
Select sync project.
If you are getting an error like "Project with path':signature-pad' could not be found in project ':app'", then please use the second way:
Select menu File -> New -> Import Module...:
After clicking on Import Module,
give the path of library like as my MacBook path:
Click on Finish. Now your library are added.
After importing the ABS Module (from File > Project Structure) and making sure it has Android 2.2 and Support Library v4 as dependencies, I was still getting the following error as you #Alex
Error retrieving parent for item: No resource found that matches the given name 'Theme.Sherlock.Light.DarkActionBar'
I added the newly imported module as a dependency to my main app module and that fixed the problem.
To resolve this problem, you just need to add the abs resource path to your project build file, just like below:
sourceSets {
main {
res.srcDirs = ['src/main/res','../../ActionBarSherlock/actionbarsherlock/res']
}
}
So, I again compile without any errors.
If you have Android Studio .0.4.0, you can create a new folder in your build path, YourApp/libraries. Copy the JAR file. There in, right click on it and "Add As Library". Now you have a popup. Just select your directory and press OK, and that's it.
Simply import the Android library project as a module and in Build.gradle.
Apply plugin: 'com.android.library'
After that, follow these steps:
Right click on Module & select open Module settings
Select dependencies, click on +, select library dependencies, and add the previously imported module.
https://www.dropbox.com/s/1e3eteu3h0pmkf7/Android%20studio%20_doc.doc?dl=0 is the Dropbox link of how to add a JAR file and library project in the latest version of Android Studio 1.0.1.
Please see the documentation with screenshots. It's very easy for a new user.
I found the solution. It's so simple. Follow froger_mcs instructions.
Make sure that you make the src folder a Source folder in Project Structure -> Modules (Sources).
Basically, you can include your JAR files in three different ways. The last one is remote library that is using https://bintray.com/ jcenter online repository. But, if you do it in one of the two other ways, the JAR file will be included physically in your project. Please read this link https://stackoverflow.com/a/35369267/5475941 for more information. In this post I explained how to import your JAR file in Android studio and I explained all possible ways.
In summary, if it is like this (local address), they are downloaded and these JAR files are physically in the project:
But, if it is an internet address like this, they are remote libraries (bintray.com jcenter part) and they will be used remotely:
I hope it helps.
Open the build gradle module app file and add your dependency. If you download the library, just import and build as gradle.
Otherwise add repositories in side gradle module app:
repositories {
maven { url 'http://clinker.47deg.com/nexus/content/groups/public' }
}
The first repositories will download the library for you.
And compile the downloaded library:
compile ('com.fortysevendeg.swipelistview:swipelistview:1.0-SNAPSHOT#aar') {
transitive = true
}
If you are creating a library, you just need to import the project as import new module.
I had a different cause of the problem so for people:
repositories {
mavenCentral()
}
change mavenCentral() to jcenter() and add
allprojects {
repositories {
jcenter()
}
}
In Android Studio, go to inside app folder, and open build.gradle file. Here you will see dependencies{}. Inside it you can add the library project and synchronise. Now after synchronising the library it will be added to your project, and you can use its functions and classes in your project.
For Android Studio:
Click on Build.gradle (module: app).
And add for
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile files('libs/commons-io-2.4.jar')
}
and in your directory "app", create a directory, "libs". Add the file yourfile.jar:
Finally, compile the Gradle Files:
I also encountered the same problem then I did following things.
I import the library project into my AndroidStudio IDE as a module using menu File -> Import module menus
Then I went to my main module in which I want the library project as a dependent project
Right click on the main module (in my case its name is app) -> open module setting -> go into dependencies tab -> click on + button (you will get it on right side of window) -> click on module dependency -> select your library project from list
Apply the changes and click the OK button.
It worked for me. I hope it will help others too.
You are able to use Gradle dependency configuration[About] to add some dependency into your project
<module_name>/build.gradle
dependencies {
//<gradle_dependency_configuration> '<dependency_name>:<dependency_version>'
//e.g.
implementation 'com.android.support:appcompat-v7:1.1.1'
}
Indeed as versions are changing, so is changing the user interface and options available on the menu. After reading most of the answers to these questions I had to guess what would work for Android Studio 1.1.0.
With your mouse, select the project at the main level (this is where it shows the name of your app).
Right click, and select the menu options New, Folder, Assets Folder.
After creating the assets folder, paste or copy in it, whatever JAR file you need for your library.
From Android Studio's main menu (top of the screen) select File -> Project Structure.
Then select your project name and go to the Dependencies tab.
Click on the plus sign (+) on the lower left of the dialog box and select file dependency.
Finally open the recently created assets folder, select the JAR files that you copied, and then click apply and OK.
Clean and rebuild your project.

Android Studio: Add jar as library?

I'm trying to use the new Android Studio but I can't seem to get it working correctly.
I'm using the Gson library to serialize/deserialize JSON-objects. But the library somehow isn't included in the build.
I had created a new project with just a MainActivity.
Copied gson-2.2.3.jar in the /libs folder and added it as a library dependancy(right click->Add as library). This includes the jar in android studio so it can be referenced from the source files.
When I try to run the project it cannot compile so I added:
compile files('libs/gson-2.2.3.jar')
to the dependencies in de .gradle file. After that it compiles correctly but when running the application I get a ClassDefNotFoundException.
Does anyone know what I'm doing wrong?
I've been struggling with the same thing for many hours, trying to get the Gson jar to work no less. I finally cracked it – here are the steps I took:
Put the Gson jar (in my case, gson-2.2.4.jar) into the libs folder
Right click it and hit 'Add as library'
Ensure that compile files('libs/gson-2.2.4.jar') is in your build.gradle file (or compile fileTree(dir: 'libs', include: '*.jar') if you are using many jar files)
Edit : Use implementation files('libs/gson-2.2.4.jar') (or implementation fileTree(dir: 'libs', include: '*.jar')) in Android Studio 3.0+
Do a clean build (you can probably do this fine in Android Studio, but to make sure I navigated in a terminal to the root folder of my app and typed gradlew clean. I'm on Mac OS X, the command might be different on your system
After I did the above four, it started working fine. I think the 'Add as library' step was the one I'd previously missed, and it didn't work until I cleaned it either.
[Edit - added the build.gradle step which is also necessary as others have pointed out]
Here are the instructions for adding a local jar file as a library to a module:
Create a 'libs' folder in the top level of the module directory (the same directory that contains the 'src' directory)
In the build.gradle file add the following so that your dependencies closure has:
dependencies {
// ... other dependencies
compile files('libs/<your jar's name here>')
}
Android Studio should have already setup a gradlew wrapper. From the command line, navigate to the top level of your project (the directory that has a gradlew file).
Run ./gradlew assemble. This should compile the project with the library. You may need to fix errors in your build.gradle file as necessary.
In order to have Android Studio recognize the local jar files as libraries for support while coding in the IDE, you need to take a few more steps:
4.1. Right click on the module in the left hand panel and choose Open Library Settings.
4.2. On the left panel of the dialog, choose Libraries.
4.3. Click the + sign above the panel second from the left -> Java
4.4. Select your local jar and add it to the project.
You may need to run the above ./gradlew command one more time
In the project right click
-> new -> module
-> import jar/AAR package
-> import select the jar file to import
-> click ok -> done
Follow the screenshots below:
1:
2:
3:
You will see this:
In Android Stuido, I like use Gradle to manage Gson lib.
Add below dependency in your build.gradle file.
repositories {mavenCentral()}
dependencies {compile 'com.google.code.gson:gson:2.2.4'}
Everything is OK.
You can also see this post.
The best way to integrate third party library in Android studio
IIRC, simply using "Add as library" isn't enough for it to compile with the project.
Check Intellij's help about adding libraries to a project
The part that should interest you the most is this:
(In File > Project Structure) Open the module settings and select the Dependencies tab.
On the Dependencies tab, click add and select Library.
In the Choose Libraries dialog, select one or more libraries and click Add Selected.
If the library doesn't show up in the dialog, add it in the Libraries settings, right below Modules.
You shouldn't need to add compile files() anymore, and the library should be properly added to your project.
All these solutions are outdated. It's really easy now in Android Studio:
File > New Module...
The next screen looks weird, like you are selecting some widget or something but keep it
on the first picture and below scroll and find "Import JAR or .AAR Package"
Then take Project Structure from File menu.Select app from the opened window then select dependencies ,then press green plus button ,select module dependency then select module you imported then press OK
Easy steps to add external library in Android Studio
If you are in Android View in project explorer, change it to Project view as below
Right click the desired module where you would like to add the external library, then select New > Directroy and name it as
'libs'
Now copy the blah_blah.jar into the 'libs' folder
Right click the blah_blah.jar, Then select 'Add as Library..'. This will automatically add and entry in build.gradle as compile
files('libs/blah_blah.jar') and sync the gradle. And you are done
Please Note : If you are using 3rd party libraries then it is better to use dependencies where Gradle script
automatically downloads the JAR and the dependency JAR when gradle
script run.
Ex : compile 'com.google.android.gms:play-services-ads:9.4.0'
Read more about Gradle Dependency Mangement
'compile files...' used to work for me, but not any more. after much pain, I found that using this instead works:
compile fileTree(dir: 'libs', include: '*.jar')
I have no idea why that made a difference, but, at least the damn thing is working now.
Download Library file from website
Copy from windows explore
Paste to lib folder from Project Explorer
Ctrl+Alt+Shift+S open Project Structure
Select Dependencies Tab, add the file by using +
Tool bar Sync project with gradle file by using button
That solved my problem. Try, if anyone want more details let me know.
I made it work by just adding one line to build.gradle:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) ----> AS creates this
implementation 'com.google.code.gson:gson:2.3.1' ----------> I added this one
}
Do not forget to click Sync now in the top right corner.
I'm using Android Studio 1.0.1.
I found Dependency Manager of Android Studio quite handy and powerful for managing 3rd party dependencies (like gson mentioned here). Providing step by step guide which worked for me (NOTE: These steps are tested for Android Studio 1.6 and onward versions on Windows platform).
Step-1:
Goto "Build > Edit Libraries and Dependencies..." it would open up the dialog "Project Structure"
Step-2:
Select "app" and then select "Dependencies" tab. Then select "Add > 1 Library dependency"
Step-3:
"Choose Library Dependency" dialog would be shown, specify "gson" in search and press the "search button"
Step-4:
The desired dependency would be shown in search list, select com.google.code.gson:gson:2.7 (this is the latest version at the time when I wrote the answer), press OK
Press OK on "Project Structure" dialog. Gradle would update your build scripts accordingly.
Hope this would help :)
1. Put the jar (in my case, gson-2.2.4.jar) into the libs folder.
2. Ensure that compile files (libs/gson-2.2.4.jar) is in your build.gradle file.
3. Now Click on the "Sync Project with Gradle files"(Left to AVD manager Button on the topbar).
After I did the above three, it started working fine.
Download & Copy Your .jar file in libs folder then adding these line to build.gradle:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.code.gson:gson:2.3.1'
}
Do not forget to click "Sync now"
You can do this with two options.
first simple way.
Copy the .jar file to clipboard then add it to libs folder. To see libs folder in the project, choose the project from combobox above the folders.
then right click on the .jar file and click add as a library then choose a module then ok.
You can see the .jar file in build.gradle file within dependencies block.
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:21.0.3'
implementation project(':okhttp-2.0.0')
implementation 'com.google.code.gson:gson:2.3.1'
}
Second way is that: We can add a .jar file to a module by importing this .jar file as a .jar module then add this module to any module we want.
import module ---> choose your .jar file --> than import as a .jar --
Then CTRL+ALT+SHIFT+S --> project sturure -->choose the module you want ato add a jar -->Dependencendies --> Module Dependency. build.gradle of the module will updated automatically.
Ive done above 3 steps and its work charm for me.
(I am using Android Studio 2.1.2)
Step 1
Add your jar package name (as an example compile 'com.squareup.okhttp3:okhttp:3.3.1') into gradle build script under build.gradle(Module:app).
Step 2:
Right click on app folder -> New -> Module
Step 3: Click Import JAR/.AAR Package Then browse your package. as an example: OkHttp.jar
With Android Studio 3+:
You should just be able to simply copy the jar file to the libs folder right under the app folder.
... myproject\app\libs\myfile.jar
Then select Project Files from the drop-down on the Projects window, right click on the project, select Synchronize to see the file in Project Files. It will automatically add the dependencies in the gradle file (Module:app).
dependencies {
...
implementation files('libs/myfile.jar')
Here is another solution:
Go to the Project Files view (select Project Files from the dropdown).
Select New... Directory, create a folder named libs right under app.
Open up File Explorer, copy and paste your jar file into the libs folder.
In Android Studio, right click on the jar file, and select Add as a Library... from the popup menu.
You should see the file listed in the dependencies list in the gradle file:
dependencies {
...
implementation files('libs/myfile.jar')
}
Open up your java file, and add the import statement there:
import com.xxx.xxx;
Put the .jar files in libs folder of the Android project.
Then add this line of code in the app's gradle file:
compile fileTree(dir: 'libs', include: ['*.jar'])
For Android gradle plugin 3.0 and later, it is better to use this instead:
implementation fileTree(dir: 'libs', include: ['*.jar'])
Unlike Eclipse we don't need to download jar and put it in /libs folder. Gradle handles these things we only need to add Gradle dependencies, Gradle downloads it and puts in gradle cache.
We need to add dependencies as:
dependencies {implementation 'com.google.code.gson:gson:2.2.4'}
thats it
However we can also download jar & add that as library but the best practice is to add Gradle dependencies.
menu File -> project struct -> module select "app" -> dependencies tab -> + button
-> File dependency -> PATH/myfile.jar
Step 1 : Now under your app folder you should see libs, if you don't see it, then create it .
Step 2 : Drag & Drop the .jar file here, you may be get a prompt "This file does not belong to the project", just click OK Button .
Step 3 : Now you should see the jar file under libs folder, right click on the jar file and select "Add as library", Click OK for prompt "Create Library"
Step 4 : Now this jar has been added.
1) create an 'your_libs' folder inside the Project/app/src folder.
2) Copy your jar file into this 'your_libs' folder
3) In Android Studio, go to File -> Project Structure -> Dependencies -> Add -> File Dependency and navigate to your jar file, which should be under 'src/your_libs'
3) Select your jar file and click 'Ok'
and then you can see on your build.gradle like this : compile
files('src/your_libs/your.jar')
In android Studio 1.1.0 .
I solved this question by following steps:
1: Put jar file into libs directory. (in Finder)
2: Open module settings , go to Dependencies ,at left-bottom corner there is a plus button. Click plus button then choose "File Dependency" .Here you can see you jar file. Select it and it's resolved.
I have read all the answers here and they all seem to cover old versions of Android Studio!
With a project created with Android Studio 2.2.3 I just needed to create a libs directory under app and place my jar there.
I did that with my file manager, no need to click or edit anything in Android Studio.
Why it works? Open Build / Edit Libraries and Dependencies and you will see:
{include=[*.jar], dir=libs}
In your project-name/app folder, find the libs folder. If there is no libs folder, create one. Add your .jar file. Right-click on it and you will find add .jar as a dependency. You can find the dependencies added to your build.gradle file.
On Mac OS X:
Add jar as library (drag jar to libs, right click add as lib)
Add compile statement to build.grade
Install gradle v1.6 (use homebrew)
brew install gradle
gradle -v
if not v1.6, upgrade homebrew
gradle clean (rebuild android did not work)
This sorted me out.
My answer is basically gathering some of the right but incomplete answers provided above.
Open build.gradle
Add the following:
dependencies {
compile 'com.android.support:appcompat-v7:19.+'
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.3'
}
This will allow support for two different ways of adding dependencies. The compile fileTree(dir: 'libs', include: ['*.jar']) (as #Binod mentioned) tells the compiler to look under the folder libs for ANY jar. It is a good practice to create such a folder 'libs' which will contain the jar packages that our application needs to use.
But this will also allow support for Maven dependency. The compile 'com.google.code.gson:gson:2.3' (as mentioned by #saneryee) it is another recommended way to add dependencies that are in a central remote repository and not in our /libs "local repository". It is basically telling gradle to look for that version of that package and it's telling the compiler to consider it when compiling the project (having it in the classpath)
PS: I use both
Like many before pointed out you shall add
compile files('libs/gson-2.2.3.jar')
to your build.gradle file.
However I have a project in Android Studio that was migrated from Eclipse and in this case the "libs" folder is named "lib" so for me removing the "s" solved the problem.
Added the libs folder at the level of app.
Added all the jars in this project.
Next, selected all the jars, in the libs folder,
right click on the selected items, and say add library
then you will find the jars expansion option, within the project explorer itself.
I observed CTRL + ALT + SHIFT + S --> project structure --> app-module -->Dependencies" already had an entry as (dir: 'libs', include: '*.jar') under compile-option, initially. And after adding the jar's as per the steps stated above, the build.gradle got the entries for the new added jar's, itself.
In Android Studio 2.1 I follow the this way,
Goto app -> src-> main -> assets folder (If not available create it) -> put your JAR files
In your build.gradle add dependency like this,
implementation files('src/main/assets/jsoup.jar')
implementation files('src/main/assets/org-apache-xmlrpc.jar')
implementation files('src/main/assets/org.apache.commons.httpclient.jar')
implementation files('src/main/assets/ws-commons-util-1.0.2.jar')
Sync now.
Now your JAR files ready to use.
For newer Android 1.0.2 the following is already there in your build.gradle file
implementation fileTree(include: ['*.jar'], dir: 'libs')
Add the library jar to your libs folder -> right click the library -> click add as a library -> it asks you for the project to add it for -> select your project-> click ok
The following line is automatically added to build.gradle
implementation files('libs/android-query.jar')
That did it for me. nothing more was required. i have shown this for android aquery another third party library for android.

Categories

Resources