Skip to content
Advertisement

Android: pass data from initial activity (launching Zxing scanner) to onActivityResult callback

I use the library zxing-android-embedded in my Android App. Before calling initiateScan() method to start the scanner from my activity, I set a class variable scanedItemId to know on which item I clicked to scan:

[...]
scanedItemId = currentItem.id // The current item where we clicked on.
IntentIntegrator qrCodeScanner = new IntentIntegrator(MyActivity.this);
qrCodeScanner.setOrientationLocked(false);
qrCodeScanner.initiateScan();
[...]

Then I get the result via onActivityResult method. It works well but my class variable scanedItemId is null because the activity is relaunched. Is it possible to keep my initial instance of MyActivity (with the scanedItemId well set) or to pass the value I need thru the IntentIntegrator to get it back on the new instance of MyActivity?

[...]
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case IntentIntegrator.REQUEST_CODE:
            // Here the scanedItemId is always null.
[...]

If possible I wouldn’t like to use a hard persistence (like db or file) to get my scanedItemId value.

Hope it’s clear enough

Advertisement

Answer

You can add more custom data like this :

scanedItemId = currentItem.id // The current item where we clicked on.
IntentIntegrator qrCodeScanner = new IntentIntegrator(MyActivity.this);
quCodeScanner.addExtra("ITEM_ID", scanedItemId);//add your data
qrCodeScanner.setOrientationLocked(false);
qrCodeScanner.initiateScan();

Because library which you used didn’t return your data. You can fork that library and add some code like below:

In CaptureManager class edit initializeFromIntent method

if (intent != null) {
    data = intent.getIntExtra("ITEM_ID", 0);//save your data
}

and resultIntent method

intent.putExtra("ITEM_ID", data);//return your data

Now in onActivityResult you can get your data

IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);
if (result.getOriginalIntent().hasExtra("ITEM_ID")) {
    Toast.makeText(this,"Item Id : " + String.valueOf(result.getOriginalIntent().getIntExtra("ITEM_ID",0)), Toast.LENGTH_LONG).show();
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement