Search code examples
androidzxing

multiple buttons scanning barcodes zxing


I am using zxing for scanning barcodes. I need to use 2 buttons for scanning. one will do one task when barcode is scanned and the other will do something else. I want to handle the click like this.

@Override
public void onClick(View v) {

    switch (v.getId()) {

        case R.id.scanone:
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();
            break;

        case R.id.scantwo:
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();
            break;

        default:
            break;
    }

}

How can I differentiate which button was called in onActivityResult() method

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

Solution

  • you may add a class-scope variable that will store the MODE or TYPE you are running, on each button set a different value for this variable, and onActivityResult() based on that variable, you decide how to process the result.

    ex,

    //class scope
    int mode = 0;
    

    onClick will be like this:

    @Override
    public void onClick(View v) {
    
        switch (v.getId()) {
    
            case R.id.scanone:
                mode = 1;
                break;
    
            case R.id.scantwo:
                mode = 2;
                break;
    
            default:
                break;
        }
    
        //starting scanner code is the same, no need to write it in each case:
        IntentIntegrator scanIntegrator = new IntentIntegrator(this);
        scanIntegrator.initiateScan();
    }
    

    and onActivityResult:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    
        //if resultCode OK...
        //if scan result not null...
    
        if(mode == 1){
            doActionOne();
        }else if (mode == 2){
            doActionTwo();
        }
    }
    

    you may need this, and you may not:

    sometimes, mode value might get lost, because the activity is paused and resumed, so you may want to save the activity state (at least mode) using onSaveInstanceState