1
public class MainActivity extends AppCompatActivity {
    TextView txt;
    Bitmap myBitmap;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = (TextView)findViewById(R.id.txt);
        ImageView myImageView = (ImageView) findViewById(R.id.imgview);
         myBitmap = BitmapFactory.decodeResource(
                getApplicationContext().getResources(),
                R.drawable.barcode);
        myImageView.setImageBitmap(myBitmap);
         btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bar();
            }
        });

    }

    public void bar(){
        BarcodeDetector detector =
                new BarcodeDetector.Builder(getApplicationContext())
                        .setBarcodeFormats(Barcode.DATA_MATRIX | Barcode.QR_CODE)
                        .build();
        if(!detector.isOperational()){
            txt.setText("Could not set up the detector!");
            return;
        }
        Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
        SparseArray<Barcode> barcodes = detector.detect(frame);
        Barcode thisCode = barcodes.valueAt(0);
        txt.setText(thisCode.rawValue);
        Toast.makeText(getApplicationContext(), thisCode.rawValue.toString(), Toast.LENGTH_SHORT).show();

    }
}

The barcode.png is: food barcode

Whenever I run the app using this as the Bitmap it crashes giving the out of bounds array 0 exception. I am not sure why this is happening but the app keeps on crashing.

It can detect the square bar codes, but it cannot detect this one. What is the issue here?

LOGCAT: Logcat from app

Fernando Gallego
  • 4,064
  • 31
  • 50
DilllyBar
  • 59
  • 1
  • 7

1 Answers1

0

The barcodes array is a SparseArray, that means that there could be gaps in the returned values, it could also be empty.

You should iterate over the keys and then retrieve the values from the SparseArray like this:

for (int i = 0; i < barcodes.size(); i++) {
    Barcode barcode = barcodes.get(barcodes.keyAt(i));
    String value = barcode.displayValue;
}
Fernando Gallego
  • 4,064
  • 31
  • 50