我正在尝试使用新的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。

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


当前回答

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

其他回答

与Eclipse不同,我们不需要下载jar并将其放在/libs文件夹中。Gradle处理这些事情,我们只需要添加Gradle依赖项,Gradle下载并放入Gradle缓存。

我们需要添加依赖项如下:

依赖项{实现'com.google.code.gson:gson:2.2.4'}

这是它 然而,我们也可以下载jar并将其添加为库,但最好的做法是添加Gradle依赖项。

在Mac OS X上:

将jar添加为库(将jar拖到libs,右键单击添加为库) 在build.grade中添加compile语句 安装gradle v1.6(使用自制软件) Brew install gradle gradle - v 如果不是v1.6,升级homebrew Gradle清洁(重建android不工作)

这让我理清了思路。

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

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

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

我已经阅读了这里所有的答案,它们似乎都涵盖了旧版本的Android Studio!

用Android Studio 2.2.3创建一个项目,我只需要在app下创建一个libs目录,并将我的jar放在那里。 我是用我的文件管理器完成的,不需要在Android Studio中点击或编辑任何东西。

为什么有效?打开构建/编辑库和依赖项,你会看到:

{include=[*.jar], dir=libs}

的编译文件…“以前为我工作,但现在不是了。在经历了很多痛苦之后,我发现用这个方法是有效的:

编译fileTree(dir: 'libs',包括:'*.jar')

我不知道为什么会有不同,但是,至少这该死的东西现在开始工作了。