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

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


当前回答

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

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

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

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

其他回答

我不知道为什么,但我的Android Studio 0.8.14疯狂时,我试图实现这些解决方案使用Gradle。我承认我对这个伟大的构建工具知之甚少,但Studio为什么会破坏我的项目?我设法让它以这种方式工作:将android-support-v13.jar放入“libs”目录,然后在我的项目上F4,并在我指向android-support-v13.jar的地方添加文件依赖。

IIRC,简单地使用“Add as library”是不足以让它与项目一起编译的。

查看Intellij关于向项目中添加库的帮助

你应该最感兴趣的部分是:

(在文件>项目结构中)打开模块设置并选择Dependencies选项卡。 在Dependencies选项卡上,单击add并选择Library。 在“选择库”对话框中,选择一个或多个库,然后单击“添加选定”。

如果库没有显示在对话框中,将其添加到Libraries设置中,就在Modules的正下方。

您不应该再需要添加compile files(),并且应该将库适当地添加到项目中。

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

在Android Studio 2.1中,我遵循这种方式,

Goto app -> src->主->资产文件夹(如果不可用创建它)->放你的JAR文件

在你的构建中。Gradle像这样添加依赖,

implementation files('src/main/assets/jsoup.jar')
implementation files('src/main/assets/org-apache-xmlrpc.jar')
implementation files('src/main/assets/org.apache.commons.httpclient.jar')
implementation files('src/main/assets/ws-commons-util-1.0.2.jar')

现在同步。 现在您的JAR文件可以使用了。

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

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