I'm new in NFC and i am developing an android application to read and write data in an nfc, but i'm having some problems.
it's code i'm using (WRITE):
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
Toast.makeText(this, R.string.message_tag_detected, Toast.LENGTH_SHORT).show();
}
Tag currentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] id = currentTag.getId();
String myData = "ABCDEFGHIJKL";
for (String tech : currentTag.getTechList()) {
if (tech.equals(NfcV.class.getName())) {
NfcV tag5 = NfcV.get(currentTag);
try {
tag5.connect();
int offset = 0;
int blocks = 8;
byte[] data = myData.getBytes();
byte[] cmd = new byte[] {
(byte)0x20,
(byte)0x21,
(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
(byte)0x00,
(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00
};
System.arraycopy(id, 0, cmd, 2, 8);
for (int i = 0; i < blocks; ++i) {
cmd[10] = (byte)((offset + i) & 0x0ff);
System.arraycopy(data, i, cmd, 11, 4);
response = tag5.transceive(cmd);
}
}
catch (IOException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
return;
}
}
}
}
When i read a tag in app TagInfo, the output is:
[00] . 41 42 43 44 [ABCD]
[01] . 42 43 44 45 [BCDE]
[02] . 43 44 45 46 [CDEF]
[03] . 44 45 46 47 [DEFG]
[04] . 45 46 47 48 [EFGH]
[05] . 46 47 48 49 [FGHI]
[06] . 47 48 49 4A [GHIJ]
[07] . 48 49 4A 4B [HIJK]
[08] . 00 00 00 00 [. . . .]
. . .
Is this output correct?
If 'NOT', where am i going wrong?
To me this looks wrong but not an expert in NfcV only used NDEF nfc cards.
[00] . 41 42 43 44 [ABCD]
[01] . 45 46 47 48 [EFGH]
[02] . 49 4A 4B 4C [IJKL]
As the what actually your are wanting to do
I think the problem lies with System.arraycopy(data, i, cmd, 11, 4);
You are copying 4 bytes of data from your source data array but only incrementing the start position by 1 byte of data hence the next block start on letter later.
I think System.arraycopy(data, i*4, cmd, 11, 4);
would produce the results you want.
As this increments the start of the arraycopy in the source data by the number of bytes you have already stored.
As you 12 bytes of data and each block stores 4 bytes you only need to use 3 blocks, so only loop 3 times by setting int blocks = 3;
otherwise you will run out of data to copy in to cmd to send to the card generating IndexOutOfBoundsException
from arraycopy
If you don't have a multiple of 4 bytes of data you will have to pad the data with zeros to be a multiple of 4 bytes OR handle a IndexOutOfBoundsException
from arraycopy
to correctly copy the remaining bytes.