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?
With Android Studio 3+:
You should just be able to simply copy the jar file to the libs folder right under the app folder.
... myproject\app\libs\myfile.jar
Then select Project Files from the drop-down on the Projects window, right click on the project, select Synchronize to see the file in Project Files. It will automatically add the dependencies in the gradle file (Module:app).
Here is another solution:
Go to the Project Files view (select Project Files from the dropdown).
Select New... Directory, create a folder named libs right under app.
Open up File Explorer, copy and paste your jar file into the libs folder.
In Android Studio, right click on the jar file, and select Add as a Library... from the popup menu.
You should see the file listed in the dependencies list in the gradle file:
Open up your java file, and add the import statement there:
IIRC, simply using "Add as library" isn't enough for it to compile with the project.
Check Intellij's help about adding libraries to a project
The part that should interest you the most is this:
If the library doesn't show up in the dialog, add it in the Libraries settings, right below Modules.
You shouldn't need to add
compile files()
anymore, and the library should be properly added to your project.Create a folder libs. Add your .jar file. Right click on it and you will find add jar as dependency. Click on it. Its all you need to do. You can find the dependencies added to your build.gradle file.
In Android Stuido, I like use Gradle to manage Gson lib.
Add below dependency in your build.gradle file.
Everything is OK.
You can also see this post. The best way to integrate third party library in Android studio
That solved my problem. Try, if anyone want more details let me know.