Search code examples
javaandroidmavenzxingqr-code

ZXing QR code scanner embedded pressing back button during scan issue


I have the following scenario : I used the Maven repository from Gradle to integrate ZXing into my Android app.

In my scan activity, the code looks like this :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scan_layout);

    IntentIntegrator integrator = new IntentIntegrator(this);
    integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
    integrator.setPrompt(" ");
    integrator.setScanningRectangle(700, 700);
    integrator.setResultDisplayDuration(0);
    integrator.setCameraId(0);  // Use a specific camera of the device
    integrator.initiateScan();
}

  public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    //retrieve scan result
    IntentResult scanningResult = null;
    scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

    if (scanningResult != null) {
     //we have a result
        String scanContent = scanningResult.getContents();

        if(isConnected()) {
            requestdata("http://rm360project-001-site1.smarterasp.net/api/endpoint", scanContent);
        }else {
            Toast.makeText(this, "Internet Connection not available", Toast.LENGTH_LONG).show();
        }
    } else {
        Intent getMainScreen = new Intent(ScanScreen.this, MainActivity.class);//pentru test, de sters
        startActivity(getMainScreen);
    }
}

The way I want it to work :
1. If I scan a QR code, call the function requestdata
2. If I press back during scan, go to MainActivity

The problem : Even when I press back on my device, the function requestdata is called, I think because scaningResult is never null. Shouldn't it be null when back is pressed? Do you have any ideea why this happens? Thank you!


Solution

  • Don't know if your still interested but...
    Simply change this line:

         if (scanningResult != null) {
    

    To this:

         if (scanningResult != null && resultCode==RESULT_OK) {
    

    For some reason simply scanningResult does not actually return null as suggested by the ZXing team, even when the Intent is canceled.