Search code examples
javajarqr-codezxingnosuchmethoderror

Exception java.lang.NoSuchMethodError with qrgen and zxing libraries


Normally, I use maven in my project but because of some migration problems I have to (temporally) download jars.

I want to use the following code:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class Main {
    public static void main(String[] args) {
        ByteArrayOutputStream out = QRCode.from("Hello World")
                                        .to(ImageType.PNG).stream();

        try {
            FileOutputStream fout = new FileOutputStream(new File(
                    "C:\\QR_Code.JPG"));

            fout.write(out.toByteArray());

            fout.flush();
            fout.close();

        } catch (FileNotFoundException e) {
            // Do Logging
        } catch (IOException e) {
            // Do Logging
        }
    }
}

I added one jar to my project:

qrgen-1.3.jar

but then, I had got an exception:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/zxing/Writer

so I added two other jars:

zxing-core-1.7.jar
zxing-j2se-1.7.jar

and now, I have got another error:

Exception in thread "main" java.lang.NoSuchMethodError: com.google.zxing.Writer.encode(Ljava/lang/String;Lcom/google/zxing/BarcodeFormat;IILjava/util/Map;)Lcom/google/zxing/common/BitMatrix;

and here I cannot fix it.

Where could be a problem?

I am sure it goes from first line fo my code:

ByteArrayOutputStream out = QRCode.from("Hello World").to(ImageType.PNG).stream();

Solution

  • Well, you are using this library with the wrong version of zxing. Looks like 1.3 uses 2.0, and you are pairing it with 1.7: https://github.com/kenglxn/QRGen/blob/e74f7912e19eb99c84100d5840e2be2e48108747/pom.xml#L40

    This is almost always what these kinds of errors mean. Using a tool like Maven avoids this. Also, both versions of these dependencies are old now.