Search code examples
javaandroidandroid-intentzxingonactivityresult

After calling zxing scanner, I go back to my activity but in a new instance


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.

My issue is that when the scanner activity finished, it goes back to my activity, but in a new instance and not the initial one (I checked with a break point in the onCreate method). So, my class variable is null. What can I do to keep my initial activity instance live and be sure the scanner goes back to it?

public class MyActivity
[...]
scanedItemId = currentItem.id // The current item where we clicked on.
IntentIntegrator qrCodeScanner = new IntentIntegrator(this);
qrCodeScanner.setOrientationLocked(false);
qrCodeScanner.initiateScan();
[...]
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.
[...]
```

Solution

  • You asked:

    What can I do to keep my initial activity instance live and be sure the scanner goes back to it?

    You can't. When your app goes to the background and the scanner app needs resources, Android will kill your app to make the resources available to the scanner app. This is normal and your app needs to be made robust enough to deal with this. If you need to keep track of your app's state so that you can continue when your app returns to the foreground, then you need to save that information somewhere persistent. You have choices:

    • SharedPreferences
    • SQLite database
    • Use a file
    • Implement onSaveInstanceState()