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

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


当前回答

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

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

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

其他回答

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

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

别忘了按“立即同步”

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

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

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

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

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

在Mac OS X上:

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

这让我理清了思路。

我已经为同样的事情挣扎了好几个小时,试图让Gson罐子工作。我终于破解了——下面是我采取的步骤:

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

在我完成以上四项之后,它开始正常工作。我认为“添加为库”步骤是我之前错过的一个步骤,直到我清理它它才开始工作。

[编辑-添加构建Gradle步骤也是必要的,正如其他人指出的那样]

下面是将本地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