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

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


当前回答

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

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

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

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

其他回答

以上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

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

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

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

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

我发现Android Studio的依赖管理器非常方便和强大的管理第三方依赖(如这里提到的gson)。提供一步一步的指导,这对我来说是有效的(注:这些步骤是针对Android Studio 1.6和Windows平台上的后续版本进行测试的)。

步骤1: 点击“Build > Edit Libraries and Dependencies…”,打开对话框“Project Structure”

步骤2: 选择“app”,然后选择“Dependencies”选项卡。然后选择“Add > 1 Library dependency”

步骤3: 弹出“选择库依赖项”对话框,在搜索中指定“gson”,然后按“搜索按钮”

步骤4: 所需的依赖项将显示在搜索列表中,选择com.google.code.gson:gson:2.7(这是我写答案时的最新版本),按OK

在“项目结构”对话框中按OK。Gradle会相应地更新你的构建脚本。

希望这能有所帮助:)