Santhosh
Santhosh

Reputation: 5016

NFC tag reading problem

This is my code to read the NFC tag. Why authentication is failing always? It is detecting the card but not reading the data. Could you please help me? Why if block is not executing? Where i'am wrong?

void resolveIntent(Intent intent)
{ 
String action = intent.getAction();

if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action))
{ 
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

    MifareClassic mfc = MifareClassic.get(tagFromIntent); 
    byte[] data;

    try
    {    
        mfc.connect();
        boolean auth = false;
        String cardData = "";

        int sectorCount = mfc.getSectorCount();
        int blockCount = 0;
        int blockIndex = 0;
        for(int j = 0; j < sectorCount; j++)
        { 
            auth = mfc.authenticateSectorWithKeyA(j, MifareClassic.KEY_DEFAULT);
            if(auth)
            {

                blockCount = mfc.getBlockCountInSector(j);
                blockIndex = 0;
                for(int i = 0; i < blockCount; i++)
                {
                    blockIndex = mfc.sectorToBlock(j);

                    data = mfc.readBlock(blockIndex);    

                    cardData = cardData + getHexString(data, data.length);
                    blockIndex++;
                }
            }

            else
            { 
                // Authentication failed - Handle it
                showAlert(AUTH); //this alert message is executing always
            }
        } 
        Toast.makeText(getApplicationContext(), cardData, Toast.LENGTH_LONG).show();
    }
    catch (IOException e)
    { 
        Log.e(TAG, e.getLocalizedMessage());
        showAlert(NETWORK);
    }
   }//end of if
}// End of method

Upvotes: 0

Views: 2328

Answers (2)

bangdao hu
bangdao hu

Reputation: 1

Try to use MifareClassic.KEY_NFC_FORUM as the keyA.

Upvotes: 0

Ben Ward
Ben Ward

Reputation: 884

Since it is not a new tag, and has been written by another app, I would suspect that the authentication key has changed. You are using the default keys, but the other app may have changed them. The older Nokia phones do this all the time. In that case instead of using MifareClasic.KEY_DEFAULT, you will need to figure out what the new key is for keyA

Upvotes: 3

Related Questions