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

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


当前回答

在Mac OS X上:

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

这让我理清了思路。

其他回答

下面是将本地jar文件作为库添加到模块的说明:

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

我的答案基本上是收集了上面提供的一些正确但不完整的答案。

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.

但这也将允许对Maven依赖项的支持。编译'com.google.code.gson:gson:2.3'(正如@saneryee所提到的)是另一种推荐的方法,可以在中央远程存储库中添加依赖项,而不是在我们的/libs“本地存储库”中。它基本上是告诉gradle寻找该包的版本,并告诉编译器在编译项目时考虑它(在类路径中)

PS:我两者都用

我只需要在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
}

不要忘记点击右上角的“立即同步”。

我使用的是Android Studio 1.0.1。

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

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

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

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

从网站下载图书馆文件 从窗口复制 从项目资源管理器粘贴到lib文件夹 Ctrl+Alt+Shift+S打开项目结构 选择Dependencies选项卡,使用+添加文件 工具栏通过按钮将项目与gradle文件同步

这解决了我的问题。试试,如果有人想知道更多细节,请告诉我。