Tuesday, July 26, 2016

How to Compile ZXING Barcode Scanner App in Android Studio Part 2

This is a follow-up from the previous post. Here, I will cover how to compile only from source files, without using pre-built jar files.

We will resume from where we left off from the previous post. Select File -> Project Structure and click on + icon. Select Java Library and set the library name as core and edit the package to be com.google.zxing. Leave class name as MyClass, as we will delete this file in a moment.

When the module has been created, you will see core directory in the project's root directory. Copy all files and folders from zxing source directory, i.e., zxing/core/src/main/java/com/google/zxing/ to the project's core/src/main/java/com/google/zxing/ directory. Delete MyClass.java file, which has been automatically created by Android Studio when creating this module.

Next, you will need to add module dependency. Add the following lines to app module's build.gradle file:
...
dependencies {
    compile project(':core')
}

Lastly, you will also need to add zxing/android-core module into this project. Since this consists of only a single file, it is easiest to simply copy this file into the app module. Copy zxing/android-core/src/main/java/com/google/zxing/client/android/camera/CameraConfigurationUtils.java file from the zxing source directory into the project's app/src/main/java/com/google/zxing/client/android/camera/ directory. Note that this is the app module's directory, not core library's directory.

Now, you should be able to compile the project!


NOTE: Depending on your configuration, you may receive an error similar to:
Error:Error converting bytecode to dex:
Cause: Dex cannot parse version 52 byte code.
This is caused by library dependencies that have been compiled using Java 8 or above.
If you are using the 'java' gradle plugin in a library submodule add 
targetCompatibility = '1.7'
sourceCompatibility = '1.7'
to that submodule's build.gradle file.

To resolve this, simply do what it asks. That is, copy the above two lines of codes into core module's build.gradle file, which should look similar to:
apply plugin: 'java'

targetCompatibility = '1.7'
sourceCompatibility = '1.7'

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

3 comments: