chariotsolutions / phonegap-nfc

PhoneGap NFC Plugin
MIT License
706 stars 555 forks source link

Error Removing MimeType Filters #364

Closed kas84 closed 4 years ago

kas84 commented 5 years ago

I am developing an App that needs to have both reading capabilities and writing capabilities.

At first the app launches in "reading mode". For that I add a mimeType listener: nfc.addMimeTypeListener and then go into reader mode: nfc.readerMode.

When I click to go into writer mode, so I disable readerMode: nfc.disableReaderMode and remove the mimeType listener: nfc.removeMimeTypeListener then I go into writer mode with nfc.addTagDiscoveredListener(nfcService.writeTag where I add a writeTag function.

After I finish, I go back to reading mode, and works just fine.

The problem is, if I try to go back to writing mode again I get this error message: "Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference"

Am I doing anything wrong?

don commented 4 years ago

When you enable readerMode, Android should ignore the code that dispatches to the listeners. If it doesn't cause an error, leave the listeners in place when you're in readerMode. Disabling reader mode should put things back like they were

That said, I don't like the remove*Listener functions, they're always causing problems. I typically keep the listener and ignore the callback if the application doesn't want to handle it. Android is only ever going to call the most specific listener so this isn't typically a problem. When we originally wrote the plugin, we were mirroring the Android APIs. It would have been better to have one listener for all NFC events. Often you can have one Javascript function handle the events for Mime, Tag, and NDEF events. Your app can keep track of if it should read or write and do the correct thing inside the callback. Since you have listeners anyway this may be a better approach than switching between readerMode and foreground scanning.

That said there's probably a way to add and remove mime listeners successfully. But IIRC this was more problematic than re-enabling Tag and NDEF listeners. If you manage to debug it, please send a pull request.