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

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


当前回答

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

其他回答

在project-name/app文件夹中,找到libs文件夹。如果没有libs文件夹,请创建一个。添加.jar文件。右键单击它,您会发现add .jar是一个依赖项。您可以找到添加到构建中的依赖项。gradle文件。

我已经为同样的事情挣扎了好几个小时,试图让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文件到剪贴板,然后将其添加到libs文件夹。要查看项目中的libs文件夹,请从文件夹上方的组合框中选择项目。

然后右键单击.jar文件,单击“添加为库”,然后选择一个模块,然后确定。 您可以在构建中看到.jar文件。Gradle文件在依赖块。

 dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:21.0.3'
        implementation project(':okhttp-2.0.0')
        implementation 'com.google.code.gson:gson:2.3.1'
    }

第二种方法是:我们可以将.jar文件作为.jar模块导入到模块中,然后将该模块添加到我们想要的任何模块中。

导入模块——>选择你的。jar文件——>而不是导入一个。jar文件——

然后按CTRL+ALT+SHIFT+S——> project sturure——>选择你想要添加一个jar的模块——>Dependencendies——> module Dependency。构建。模块的Gradle会自动更新。

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

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

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

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

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

1. 将jar(在我的例子中是gson-2.2.4.jar)放入libs文件夹。 2. 确保构建中有编译文件(libs/gson-2.2.4.jar)。gradle文件。 3.现在点击“同步项目与Gradle文件”(顶部栏左侧到AVD管理器按钮)。

在我完成以上三项之后,它开始正常工作。