Android Studio: Add jar as library?

2018-12-31 00:51发布

I'm trying to use the new Android Studio but I can't seem to get it working correctly.

I'm using the Gson library to serialize/deserialize JSON-objects. But the library somehow isn't included in the build.

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')

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?

30条回答
牵手、夕阳
2楼-- · 2018-12-31 01:39

1. Put the jar (in my case, gson-2.2.4.jar) into the libs folder.

2. Ensure that compile files (libs/gson-2.2.4.jar) is in your build.gradle file.

3. Now Click on the "Sync Project with Gradle files"(Left to AVD manager Button on the topbar).

After I did the above three, it started working fine.

查看更多
宁负流年不负卿
3楼-- · 2018-12-31 01:39

Put the .jar files in libs folder of the Android project.

Then add this line of code in the app's gradle file:

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

For Android gradle plugin 3.0 and later, it is better to use this instead:

    implementation fileTree(dir: 'libs', include: ['*.jar'])
查看更多
旧时光的记忆
4楼-- · 2018-12-31 01:39

Unlike Eclipse we don't need to download jar and put it in /libs folder. Gradle handles these things we only need to add Gradle dependencies, Gradle downloads it and puts in gradle cache.

We need to add dependencies as:

dependencies {implementation 'com.google.code.gson:gson:2.2.4'}

thats it However we can also download jar & add that as library but the best practice is to add Gradle dependencies.

查看更多
低头抚发
5楼-- · 2018-12-31 01:39
menu File -> project struct -> module select "app" -> dependencies tab -> + button 
-> File dependency -> PATH/myfile.jar
查看更多
临风纵饮
6楼-- · 2018-12-31 01:39

Like many before pointed out you shall add

compile files('libs/gson-2.2.3.jar') 

to your build.gradle file.

However I have a project in Android Studio that was migrated from Eclipse and in this case the "libs" folder is named "lib" so for me removing the "s" solved the problem.

查看更多
初与友歌
7楼-- · 2018-12-31 01:40

Step 1 : Now under your app folder you should see libs, if you don't see it, then create it .

Step 2 : Drag & Drop the .jar file here, you may be get a prompt "This file does not belong to the project", just click OK Button .

Step 3 : Now you should see the jar file under libs folder, right click on the jar file and select "Add as library", Click OK for prompt "Create Library"

Step 4 : Now this jar has been added.

enter image description here

查看更多
登录 后发表回答