Benben
Benben

Reputation: 1455

A method to decode QR Code with using loop in Android application

I am implementing an method to decode QR Code and return characters contained in a code for Android application. I'd like to run this method until QR Code is decoded successfully and return no null value.

It runs rightly at 1st loop. But when it fails to read it at 1st loop, it seldom decodes code since 2nd loop. Also sometimes it goes into an infinite loop.

If you have some tips, please let me know.

public String readQRCode(Bitmap file) {
    Reader reader = new MultiFormatReader();
    Result result = null;
    do {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_IMAGE);
        Toast.makeText(this, "Please try again", Toast.LENGTH_LONG).show();

        LuminanceSource source = new RGBLuminanceSource(file);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
                source));
        // Decode
        try {
            result = reader.decode(binaryBitmap);
        } catch (NotFoundException e) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, REQUEST_IMAGE);
            Toast.makeText(this, "Please try again", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
    } while (result == null || result.getText() == null);

    return result.getText();
}

Upvotes: 0

Views: 1087

Answers (1)

Peter
Peter

Reputation: 940

You've created what appears to be a busy wait-loop. You need to completely rewrite the logic.

startActivityForResult does not return a value, so you should never process the result in the same method were you call the activity. You should do the processing in onActivityResult.

See the documentation right here: http://developer.android.com/reference/android/app/Activity.html#StartingActivities

In your case:

  • remove the loop, don't do anything with "result" in readQRCode
  • add an onActivityResult method and do everything that comes after startActivityForResult in there
  • if you want to loop, call readQRCode from startActivityForResult

The end result should not have any kind of loop.

BTW: if you want us to correct the code, we'll also need to see what's inside your current startActivityForResult.

Upvotes: 1

Related Questions