Question

Here I am developing an adroid app which will read the records in the NFC tag. Here is the part of code in my program to read the tag, when it read, Out of bounds exception occurs.

NdefMessage[] msgs = null;
    String action = intent.getAction();
    if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)||
            NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)){
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(rawMsgs != null){
            msgs = new NdefMessage[rawMsgs.length];
            for(int i=0; i<rawMsgs.length; i++){
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        }else{
            byte[] empty = new byte[]{};
            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
            NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
            msgs = new NdefMessage[]{msg};
        }

    }
    if(msgs==null){
        String[] array = new String[]{"No Tag discovered!"};
        return array;
    }else{
        String[] array = new String[]{new String(msgs[0].getRecords()[0].getPayload()), 
                                        new String(msgs[1].getRecords()[0].getPayload())
        };
        return array;
    }

Records in tag

When I hide this sentence "new String(msgs1.getRecords()[0].getPayload())", my program can run smoothly, so I am quite sure program is in this line. May I ask how can I solve the problem?

Was it helpful?

Solution

Yes problem is sure in this line

new String[]{new String(msgs[0].getRecords()[0].getPayload()), 
                                            new String(msgs[1].getRecords([0].getPayload())

because you are try to access msgs[1].getRecords in above line. But if you see your code, in some condition like

else{
            byte[] empty = new byte[]{};
            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
            NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
            msgs = new NdefMessage[]{msg};
        }

msgs arrays contains only one element but you try to access 2nd element which will be not exist. So change your code and apply condition before access the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top