Android Studio:将 jar 添加为库? [英] Android Studio: Add jar as library?
问题描述
我正在尝试使用新的 Android Studio,但似乎无法正常工作.
I'm trying to use the new Android Studio but I can't seem to get it working correctly.
我正在使用 Gson 库来序列化/反序列化 JSON 对象.但是该库不知何故未包含在构建中.
I'm using the Gson library to serialize/deserialize JSON-objects. But the library somehow isn't included in the build.
我创建了一个只有 MainActivity 的新项目.将 gson-2.2.3.jar 复制到/libs 文件夹中并将其添加为库依赖项(右键单击 -> 添加为库).这包括 android studio 中的 jar,因此可以从源文件中引用.
I had created a new project with just a MainActivity. Copied gson-2.2.3.jar in the /libs folder and added it as a library dependancy(right click->Add as library). This includes the jar in android studio so it can be referenced from the source files.
当我尝试运行该项目时,它无法编译,所以我添加了:
When I try to run the project it cannot compile so I added:
compile files('libs/gson-2.2.3.jar')
到 de .gradle 文件中的依赖项.之后它可以正确编译,但在运行应用程序时,我得到一个 ClassDefNotFoundException
.
to the dependencies in de .gradle file. After that it compiles correctly but when running the application I get a ClassDefNotFoundException
.
有人知道我做错了什么吗?
Does anyone know what I'm doing wrong?
推荐答案
我已经为同一件事苦苦挣扎了好几个小时,试图让 Gson jar 继续工作.我终于破解了——这是我采取的步骤:
I've been struggling with the same thing for many hours, trying to get the Gson jar to work no less. I finally cracked it – here are the steps I took:
- 将 Gson jar(在我的例子中是
gson-2.2.4.jar
)放入libs
文件夹 - 右键单击它并点击添加为库"
确保
compile files('libs/gson-2.2.4.jar')
在您的build.gradle
文件(或compilefileTree(dir: 'libs', include: '*.jar')
如果你使用了很多 jar 文件)
- Put the Gson jar (in my case,
gson-2.2.4.jar
) into thelibs
folder - Right click it and hit 'Add as library'
Ensure that
compile files('libs/gson-2.2.4.jar')
is in yourbuild.gradle
file (orcompile fileTree(dir: 'libs', include: '*.jar')
if you are using many jar files)
Edit : Use implementation files('libs/gson-2.2.4.jar')
(或 implementation fileTree(dir: 'libs', include: '*.jar')
) 在 Android Studio 3.0+ 中
Edit : Use implementation files('libs/gson-2.2.4.jar')
(or implementation fileTree(dir: 'libs', include: '*.jar')
) in Android Studio 3.0+
做一个干净的构建(你可能可以在 Android Studio 中做到这一点,但为了确保我在终端中导航到我的应用程序的根文件夹并输入 gradlew clean
.我'm 在 Mac OS X 上,命令可能与您的系统不同
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
在我完成上述四个之后,它开始工作正常.我认为添加为库"步骤是我以前错过的步骤,直到我清理它才起作用.
After I did the above four, it started working fine. I think the 'Add as library' step was the one I'd previously missed, and it didn't work until I cleaned it either.
这篇关于Android Studio:将 jar 添加为库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!