Hi all,
I've previously (successfully) developed applications which detect tags and read the data off them (and then perform some logic or other but that is besides the point).
When it came to developing a new application, I decided to separate different types of logic so that the code becomes more re-usable.
I've separated it into a midlet, a form, an NFCAgent class which performs all the NFC-related logic and a class which performs operations given the NDEF-records on the tags. For some reason, despite the code being practically copy-and-pasted from my previous applications, the targetDiscovered event is simply not being triggered.
I'll post the code of the NFCAgent class so that maybe someone can help me, 'tis most confusing.
and for the context, the NFCClient class:Code:package NFC; import java.io.IOException; import java.util.Vector; import javax.microedition.contactless.*; import javax.microedition.contactless.ndef.*; import javax.microedition.io.Connector; public class NFCAgent implements TargetListener { private DiscoveryManager manager; private NDEFTagConnection connection; private NFCClient client; private boolean aborted = false; public NFCAgent(NFCClient client) { manager = DiscoveryManager.getInstance(); try { manager.addTargetListener(this, TargetType.NDEF_TAG); } catch(ContactlessException ex) { client.NFCError("Unable to initiate discovery manager: " + ex.getMessage()); } catch(IllegalStateException ex) { client.NFCError("Unable to initiate discovery manager: " + ex.getMessage()); } } public void targetDetected(TargetProperties[] prop) { aborted = false; Vector records = new Vector(); TargetProperties target = prop[0]; try { connection = (NDEFTagConnection) Connector.open(target.getUrl()); } catch (IOException ex) { client.NFCError("Unable to open connection to tag: " + ex.getMessage()); abort(); } if (!aborted) { try { NDEFMessage msg = connection.readNDEF(); NDEFRecord[] rows = msg.getRecords(); for (int i = 0; i < rows.length; i++) { NDEFRecord row = rows[i]; String str = new String(row.getPayload()); records.addElement(str); } } catch (ContactlessException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } client.targetRecordsReceived(records); } public void abort() { aborted = true; try { connection.close(); } catch (IOException ignored) { //Nothing useful we can do here... } } public void close() { manager.removeTargetListener(this, TargetType.NDEF_TAG); try { connection.close(); } catch (IOException ignored) { //Nothing useful we can do here... } } }
(I'm relatively new to Java, by the way, and have only been using it for about a week)Code:package NFC; import java.util.Vector; public interface NFCClient { public void targetRecordsReceived(Vector records); public void NFCError(String message); }
Any help would be very much appreciated.

.
Reply With Quote


