简体   繁体   English

我如何使asynctask抛出WriterException?

[英]how do i make asynctask throw WriterException?

When i try to write the code like this error occurs: 当我尝试编写类似此错误的代码时:

doInBackground(String...)' in 'com.....QrGenerator' clashes with 'doInBackground(Params...)' in 'android.os.AsyncTask'; 'com ..... QrGenerator'中的doInBackground(String ...)'与'android.os.AsyncTask'中的'doInBackground(Params ...)'相冲突; overridden method does not throw 'com.google.zxing.WriterException' 重写的方法不会引发'com.google.zxing.WriterException'

Here is the code: 这是代码:

private class QrGenerator extends AsyncTask<String,Integer,Bitmap>{
    @Override
    protected Bitmap doInBackground(String... strings) throws WriterException  {

    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < strings.length; i++) {
       strBuilder.append(strings[i]);
    }
    String value = strBuilder.toString();

    BitMatrix bitMatrix;
    try {
        bitMatrix = new MultiFormatWriter().encode(
                value,
                BarcodeFormat.DATA_MATRIX.QR_CODE,
                QRcodeWidth, QRcodeWidth, null
        );

    } catch (IllegalArgumentException Illegalargumentexception) {

        return null;
    }
    int bitMatrixWidth = bitMatrix.getWidth();

    int bitMatrixHeight = bitMatrix.getHeight();

    int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];

    for (int y = 0; y < bitMatrixHeight; y++) {
        int offset = y * bitMatrixWidth;

        for (int x = 0; x < bitMatrixWidth; x++) {

            pixels[offset + x] = bitMatrix.get(x, y) ?
                    getResources().getColor(R.color.QRCodeBlackColor) : getResources().getColor(R.color.QRCodeWhiteColor);
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);

    bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);
    return bitmap;
}

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        imageView.setImageBitmap(bitmap);
    }
}

You cannot throw additional exceptions in overriden methods, like doInBackground(...) . 您不能在诸如doInBackground(...)类的重写方法中引发其他异常。 See this link . 请参阅此链接 You have to catch the exception within your method. 您必须在方法中捕获异常。 I modified your method to also catch the WriterException. 我修改了您的方法以同时捕获WriterException。

try {
    bitMatrix = new MultiFormatWriter().encode(
            value,
            BarcodeFormat.DATA_MATRIX.QR_CODE,
            33, 33, null
    );

} catch (IllegalArgumentException | WriterException e1) {
    e1.printStackTrace();
    return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM