0

I'm developing one app on CIPHERLAB device that has two lateral physical buttons that activate the laser and can scar some barcodes.

My main issue is all what i would make it do works properly but if i get back to another activity by pressing back button and return to the same activity where i can scan the barcode the app crash if i scan another code and when i return to that activity it gives following errors and crash if i scan a code:

06-11 12:11:47.211 25170-25170/com.example.igardini.visualposmobile E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.igardini.visualposmobile, PID: 25170 android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@89ed74e is not valid; is your activity running? at android.view.ViewRootImpl.setView(ViewRootImpl.java:796) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:351) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93) at android.app.Dialog.show(Dialog.java:322) at com.example.igardini.visualposmobile.cassa.CustomAllert(cassa.java:217) at com.example.igardini.visualposmobile.cassa$2.run(cassa.java:123) at android.os.Handler.handleCallback(Handler.java:836) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:203) at android.app.ActivityThread.main(ActivityThread.java:6251) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

Here is my cassa.java activity code where i've implemented method which i use to scan the barcode with the laser and print it as a String.

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

    editText = findViewById(R.id.editTextBar);

    myDB = new DataBaseHandler(this);

    itemCassas = new ArrayList<>();
    buildTopRecyclerView();

     loadData();
     buildRecyclerView();


    price = findViewById(R.id.priceText);


    m_RM = ReaderManager.InitInstance(getApplicationContext());
    mReaderCallback = cassa.this;

    IntentFilter filter = new IntentFilter();
    filter.addAction(GeneralString.Intent_READERSERVICE_CONNECTED);
    registerReceiver(myDataReceiver, filter);


}


@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(myDataReceiver);
}

private final BroadcastReceiver myDataReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(GeneralString.Intent_READERSERVICE_CONNECTED)) {

            if(mReaderCallback != null){
                m_RM.SetReaderCallback(mReaderCallback);
            }

        }
    }
};



// getting a string of barcode after scanning it

@Override
public void onDecodeComplete(final String arg0) throws RemoteException {
    this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            editText.setText(arg0);

            // using the string got from the scanning for searching some data from the DB

            if(!TextUtils.isEmpty(editText.getText().toString())) {
                searchKeyword = editText.getText().toString();
                result = myDB.dbRawSearch(searchKeyword);

                if(result != null) {
                    String[] split = result.split("\n");

                    if (!split[0].equals("")) {
                        resultArt = myDB.dbRawArticoli(split[0]);

                        String[] splitArt = resultArt.split("\n");

                        itemCassas.add(new ItemCassa(splitArt[0], splitArt[1], Double.parseDouble(splitArt[2].replace(",", "."))));
                        exampleAdapter.notifyItemInserted(itemCassas.size());
                    } else {
                        CustomAllert();
                    }
                }
            }
        }
    });
}

@Override
public IBinder asBinder() {
    return null;
}


// Funzione per il controllo del pulsante Back
@Override
public void onBackPressed() {
    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    super.onBackPressed();

}

public void CustomAllert(){
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);

    @SuppressLint("InflateParams") View mView = getLayoutInflater().inflate(R.layout.alert_dialog, null);

    Button button = mView.findViewById(R.id.btnOK);

    mBuilder.setView(mView);
    final AlertDialog dialog = mBuilder.create();
    dialog.show();
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();

        }
    });


}
John K
  • 371
  • 5
  • 26
  • 1
    It's because you've forgotten to deallocate the resources used by the scanner, when you leave the Activity. You need to unregister any listeners, close all connection,... when the Activity stops, and register them again when the Activity is resumed – Eselfar Jun 11 '18 at 09:25
  • i've put "unregisterReceiver(myDataReceiver);" onBackPressed method but still crashing which other stuff i should put to unregister the listeners? – John K Jun 11 '18 at 09:29
  • You should provide any helpful code for us to help you. Where is the code of your `onBackPressed` method? But this shouldn't be in `onBackPressed` anyway as the all of this should be unregistered when the app is put in the background – Eselfar Jun 11 '18 at 09:43
  • @Eselfar updated with all the rest of the code – John K Jun 11 '18 at 09:45
  • @Eselfar the point is i'm unregistering it onDestroy but idk why it's not working now it's giving another error as "ava.lang.IllegalArgumentException: Receiver not registered: com.example.igardini.visualposmobile.cassa$1@30e6236 at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4298)" – John K Jun 11 '18 at 09:56
  • At least your code in `onBackPressed` is not correct. You shouldn't call `finish`, just do what you have to do and then call super. In you current implementation, all the code below `finish` is not called as `finish` terminates the Activity – Eselfar Jun 11 '18 at 09:58
  • even without finish() it's giving the same error :\ – John K Jun 11 '18 at 10:00
  • ok now it's not giving anymore the same error when i press back button but if i enter to the activity press back and return to it after scanning a code it says "Unable to add window -- token android.os.BinderProxy@89ed74e is not valid; is your activity running?" and error on my CustomAllertDialog – John K Jun 11 '18 at 10:02
  • See [this answer](https://stackoverflow.com/a/6165317/1827254). Basically you should remove `finish` from your `onBackPress` method and only call `unregisterReceiver` in `onDestroy` – Eselfar Jun 11 '18 at 10:08
  • @Eselfar yeah that's what i've done but it still giving "Unable to add window -- token android.os.BinderProxy@89ed74e is not valid; is your activity running?" – John K Jun 11 '18 at 10:10
  • 1
    There is no `CustomAllertDialog` in the code you've provided – Eselfar Jun 11 '18 at 10:12
  • @Eselfar updated code – John K Jun 11 '18 at 10:12
  • What happen is: `onDecodeComplete` is called before the BroadcastReceiver is unregistered. So `CustomAllert` (should be `customAllert`btw) is called when the Activity is destroyed, so it can't be displayed (as the Dialog relies on the Activity). Try `if (!isDestroyed() && !isFinishing())` before calling `customAllert` – Eselfar Jun 11 '18 at 10:22
  • @Eselfar ok by doing this is doesn't crash anymore but the issue remaining that if i press back and return to another activity and i reopen the activity cassa.java all the method's that works with the scanner doesn't work i mean that customAllert should be anyway visible even if i exit and return to the activity and there is no Barcode scanned in DB but that's work just at the first start of the app – John K Jun 11 '18 at 10:33
  • 1
    You probably have to release the `m_RM` too or the resource linked to the Scanner, otherwise the scanner is still in use and you can't start it again the next time you want to use it – Eselfar Jun 11 '18 at 10:47
  • 1
    @Eselfar damn the one problem was that i just had to put onDestroy also m_RM.Release(); thank you so much – John K Jun 11 '18 at 12:25

0 Answers0