我正在尝试使用新的Android Studio,但我似乎不能让它正常工作。

我正在使用Gson库来序列化/反序列化json对象。但是这个库不知何故没有包含在构建中。

我用MainActivity创建了一个新项目。 复制gson-2.2.3.jar到/libs文件夹中,并将其添加为库依赖项(右键单击->添加为库)。这包括android studio中的jar,因此可以从源文件中引用它。

当我尝试运行项目时,它无法编译,所以我添加:

compile files('libs/gson-2.2.3.jar')

到de .gradle文件中的依赖项。之后,它正确编译,但当运行应用程序时,我得到一个ClassDefNotFoundException。

有人知道我哪里做错了吗?


当前回答

下载并复制你的。jar文件到libs文件夹,然后添加这些行到build.gradle:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.code.gson:gson:2.3.1'
}

别忘了按“立即同步”

其他回答

menu File -> project struct -> module select "app" -> dependencies tab -> + button 
-> File dependency -> PATH/myfile.jar

以上3个步骤我已经做到了,它的工作魅力对我来说。

(我使用Android Studio 2.1.2)

步骤1

将你的jar包名称(例如编译'com.squareup.okhttp3:okhttp:3.3.1')添加到build.gradle(Module:app)下的gradle构建脚本中。

步骤2: 右键单击app文件夹->新建->模块

步骤3:单击“导入JAR/”。然后浏览您的包。例如:OkHttp.jar

将.jar文件放到Android项目的libs文件夹中。

然后在应用程序的gradle文件中添加这行代码:

    compile fileTree(dir: 'libs', include: ['*.jar'])

对于Android gradle插件3.0及以后版本,最好使用这个:

    implementation fileTree(dir: 'libs', include: ['*.jar'])

在我的例子中,添加的库遗漏了一些依赖项,但不幸的是,Android Studio(0.8.14)对此保密。

不需要手动配置任何东西!我只是添加了缺少的库,并在应用程序构建中使用默认的依赖项配置。Gradle文件,像这样

dependencies {
    compile 'com.google.code.gson:gson:2.+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

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