[android] How to build an android library with Android Studio and gradle?

I am trying to migrate a project from Eclipse but nothing I have tried is working. In Eclipse I have 3 projects (2 android app projects and 1 android library project). The 2 app projects depend on the library project. When I do the gradle export I get 3 projects that don't work. I am open to restructuring the project but haven't found any documentation on how this should be done.

Is there a way to make the 3 projects that Eclipse exports work together? Am I better off restructuring things and if so is documentation for how this should be done?

Update

I have uploaded the entire project to GitHub https://github.com/respectTheCode/android-studio-library-example

Update 1

Based the suggestions from Padma Kumar this is what I have tried.

  1. Create a new Project called MyApp
  2. Click File > New Module, choose Android Library and name it MyLib
  3. Click Build > Make Project

The build fails with this error

Module "MyLib" was fully rebuilt due to project configuration/dependencies changes
Compilation completed with 1 error and 0 warnings in 19 sec
1 error
0 warnings
/.../MyApp/MyLib/build/bundles/debug/AndroidManifest.xml
Gradle: <manifest> does not have package attribute.

I then added a package attribute to the manifest making it

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mylib" >

After building I get this error

Module "MyApp" was fully rebuilt due to project configuration/dependencies changes
Compilation completed with 2 errors and 0 warnings in 13 sec
2 errors
0 warnings
/.../MyApp/MyLib/src/main/java/com/example/mylib/MainActivity.java
Gradle: package R does not exist
Gradle: package R does not exist

Adding dependency doesn't seem to have any impact on the error. Continuing from above

  1. Click File > Project Structure > Modules > MyApp-MyApp
  2. Switch to Dependencies Tab
  3. Click + > Module Dependency and pick MyLib
  4. Click Apply and OK
  5. Click Build > Make Project

Update 2

Based the suggestions from Ethan this is where we get

The 2 sub project build.gradle seem to have all of the correct parts and the only difference is the plugin line bellow is the MyApp/build.gradle.

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')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

The root project build.gradle was empty so I added the two projects like this

dependencies {
    compile project(":MyLib")
    compile project(":MyApp")
}

I now get this error when building

Gradle:
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/kevin/GitHub/AppPress/MyApp/build.gradle' line: 2
* What went wrong:
A problem occurred evaluating root project 'MyApp'.
> Could not find method compile() for arguments [project ':MyLib'] on root project 'MyApp'.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Update 3

Big thanks Ethan for solving this.

  1. Add compile project(':SubProjects:MyLib') to the MyLib/build.gradle
  2. Remove compile files('libs/android-support-v4.jar') from the MyLib/build.gradle
  3. Close project and Import the root project from gradle

Update 4

As of 0.1.2 you can now include compile "com.android.support:support-v4:13.0.0" instead of compile files('libs/android-support-v4.jar'). Since it is coming from mavin now you can include this in multiple projects without problems.

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.4.2'
    }
}

apply plugin: 'android'

dependencies {
    compile "com.android.support:support-v4:13.0.0"

    compile project(':SubProjects:MyLib')
}

Update 5

As of 0.1.3 there is now a "Sync Project" button in the toolbar. You can click that instead of reimporting your project after making changes to .gradle files.

This question is related to android gradle android-studio

The answer is


I just had a very similar issues with gradle builds / adding .jar library. I got it working by a combination of :

  1. Moving the libs folder up to the root of the project (same directory as 'src'), and adding the library to this folder in finder (using Mac OS X)
  2. In Android Studio, Right-clicking on the folder to add as library
  3. Editing the dependencies in the build.gradle file, adding compile fileTree(dir: 'libs', include: '*.jar')}

BUT more importantly and annoyingly, only hours after I get it working, Android Studio have just released 0.3.7, which claims to have solved a lot of gradle issues such as adding .jar libraries

http://tools.android.com/recent

Hope this helps people!


Here is my solution for mac users I think it work for window also:

First go to your Android Studio toolbar

Build > Make Project (while you guys are online let it to download the files) and then

Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then

Run your app that is done it will launch your emulator and configure it then run it!

That is it!!! Happy Coding guys!!!!!!!


Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to android-studio

A failure occurred while executing com.android.build.gradle.internal.tasks "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Flutter plugin not installed error;. When running flutter doctor ADB.exe is obsolete and has serious performance problems Android design support library for API 28 (P) not working Flutter command not found How to find the path of Flutter SDK