Example usage for android.nfc NdefMessage getRecords

List of usage examples for android.nfc NdefMessage getRecords

Introduction

In this page you can find the example usage for android.nfc NdefMessage getRecords.

Prototype

public NdefRecord[] getRecords() 

Source Link

Document

Get the NDEF Records inside this NDEF Message.

An NdefMessage always has one or more NDEF Records: so the following code to retrieve the first record is always safe (no need to check for null or array length >= 1):

 NdefRecord firstRecord = ndefMessage.getRecords()[0]; 

Usage

From source file:com.evandroid.musica.MainLyricActivity.java

@TargetApi(14)
private Lyrics getBeamedLyrics(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    if (rawMsgs != null && rawMsgs.length > 0) {
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        NdefRecord[] records = msg.getRecords();
        if (records.length > 0) {
            try {
                return Lyrics.fromBytes(records[0].getPayload());
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();//from w  w w.ja va2 s .  com
            }
        }
    }
    return null;
}

From source file:org.protocoderrunner.apprunner.AppRunnerActivity.java

@Override
public void onNewIntent(Intent intent) {
    MLog.d(TAG, "New intent " + intent);

    if (intent.getAction() != null) {
        MLog.d(TAG, "Discovered tag with intent: " + intent);
        // mText.setText("Discovered tag " + ++mCount + " with intent: " +
        // intent);

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String nfcID = StrUtils.bytetostring(tag.getId());

        // if there is mContext message waiting to be written
        if (PNFC.nfcMsg != null) {
            MLog.d(TAG, "->" + PNFC.nfcMsg);
            PNFC.writeTag(this, tag, PNFC.nfcMsg);
            onNFCWrittenListener.onNewTag();
            onNFCWrittenListener = null;
            PNFC.nfcMsg = null;/*  w  w w  .  ja  v a 2 s  . com*/

            // read the nfc tag info
        } else {

            // get NDEF tag details
            Ndef ndefTag = Ndef.get(tag);
            if (ndefTag == null) {
                return;
            }

            int size = ndefTag.getMaxSize(); // tag size
            boolean writable = ndefTag.isWritable(); // is tag writable?
            String type = ndefTag.getType(); // tag type

            String nfcMessage = "";

            // get NDEF message details
            NdefMessage ndefMesg = ndefTag.getCachedNdefMessage();
            if (ndefMesg != null) {
                NdefRecord[] ndefRecords = ndefMesg.getRecords();
                int len = ndefRecords.length;
                String[] recTypes = new String[len]; // will contain the
                // NDEF record types
                String[] recPayloads = new String[len]; // will contain the
                // NDEF record types
                for (int i = 0; i < len; i++) {
                    recTypes[i] = new String(ndefRecords[i].getType());
                    recPayloads[i] = new String(ndefRecords[i].getPayload());
                    MLog.d(TAG, "qq " + i + " " + recTypes[i] + " " + recPayloads[i]);

                }
                nfcMessage = recPayloads[0];

            }

            onNFCListener.onNewTag(nfcID, nfcMessage);
        }

    }

}

From source file:it.imwatch.nfclottery.MainActivity.java

/**
 * Parses a discovered NDEF vCard message and stores it
 * in the app's ContentProvider. If the card contains more than one
 * for each detail type (name, organization, title, email) then they
 * are merged when inserting them in the database in a list string
 * for each type. Values in these lists are separated by  Only the first non-empty value for each type of
 * field will be shown on the UI, anyway.
 *
 * @param ndefMessage The NDEF message to parse and store data from
 *//*  ww w  .ja v  a2 s.c om*/
private void parseAndInsertVCard(NdefMessage ndefMessage) {
    NdefRecord[] records = ndefMessage.getRecords();
    ArrayList<String> names = new ArrayList<String>();
    ArrayList<String> emails = new ArrayList<String>();
    ArrayList<String> organizations = new ArrayList<String>();
    ArrayList<String> titles = new ArrayList<String>();

    // Tags might contain more than one record, each of which might contain
    // one or more of the elements (or no record, if malformed...)!
    for (NdefRecord record : records) {
        String vCardString = new String(record.getPayload());

        try {
            readDetailsFromvCard(mVCardEngine, vCardString, names, emails, organizations, titles);
        } catch (IOException e) {
            Log.e(TAG, "Error while parsing a vCard!", e);
            if (DEBUG)
                Log.v(TAG, "Malformed vCard contents:\n" + vCardString);
        }
    }

    if (emails.isEmpty()) {
        // It's mandatory to have at least one email address
        showCroutonNao(getString(R.string.error_email_not_present), Style.ALERT);
        Log.e(TAG, "The tag doesn't contain any email address");
        return;
    }

    // Now check and consolidate all emails in a CSV list
    // (to avoid looping though this list all over again later on)
    StringBuilder emailCsv = new StringBuilder();
    for (String email : emails) {
        if (DataHelper.isEmailAlreadyPresent(this, email)) {
            // we add only once every email
            showCroutonNao(getString(R.string.error_email_already_present, email), Style.ALERT);
            return;
        }

        emailCsv.append(email).append(DataHelper.VALUES_SEPARATOR);
    }

    if (DataHelper.insertContact(this, names, emailCsv.toString(), organizations, titles)) {
        showCroutonNao(getString(R.string.new_contact_added, emails.get(0)), Style.CONFIRM);
        updateParticipantsCount();
    }
}

From source file:net.lp.hivawareness.v4.HIVAwarenessActivity.java

/**
 * Parses the NDEF Message from the intent and prints to the TextView
 *//*from   w  w w .  ja v a 2 s  .c o  m*/
void processIntent(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    NdefMessage msg = (NdefMessage) rawMsgs[0];

    String data = new String(msg.getRecords()[0].getPayload());
    String[] parts = data.split("\\|");

    // record 0 contains the MIME type, record 1 is the AAR, if present
    Log.v("HIV", "old status " + caught + " " + data);

    double partnerInfected = Double.parseDouble(parts[0]);
    Gender partnerGender = Gender.valueOf(parts[1]);
    updateInfectionStatus(partnerInfected, partnerGender);

    if (!HIVAwarenessActivity.DEBUG)
        FlurryAgent.onEvent("touched");
    AnalyticsUtils.getInstance().trackGAEvent("HIVAwarenessActivity", "Touched",
            this.getLocalClassName() + ".ListClick", caught);

    Log.v("HIV", "new status " + caught);

    showDialog(SMOKING_DIALOG_ID);

}

From source file:us.rader.wyfy.MainActivity.java

/**
 * Initialize from a legacy <code>NdefMessage</code>
 * /*from   w w w. ja  v  a  2 s  .c om*/
 * Provide backward compatibility for tags written with older versions of
 * this app
 * 
 * @param ndefMessage
 *            legacy <code>NdefMessage</code>
 * 
 * @return <code>true</code> if and only if an asynchronouse attempt to
 *         connect was launched
 */
private boolean parseLegacyMessage(NdefMessage ndefMessage) {

    try {

        NdefRecord[] records = ndefMessage.getRecords();

        if (records.length > 0) {

            NdefRecord record = records[0];

            if (record.getTnf() != NdefRecord.TNF_MIME_MEDIA) {

                return false;

            }

            String type = new String(record.getType(), "US-ASCII"); //$NON-NLS-1$

            if ("application/x-wyfy".equals(type)) { //$NON-NLS-1$

                String payload = new String(record.getPayload(), "US-ASCII"); //$NON-NLS-1$
                return parseUri(payload);

            }
        }

    } catch (Exception e) {

        Log.e(getClass().getName(), "initializeNdefMessage", e); //$NON-NLS-1$

    }

    return false;

}

From source file:net.networksaremadeofstring.rhybudd.PushSettingsFragment.java

void processIntent(Intent intent) {
    //Log.e("processIntent","processIntent");
    try {//  w ww. ja  va 2 s  .c  o m
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];

        //Backup our current key
        prevFilterKey = FilterKey.getText().toString();

        // record 0 contains the MIME type, record 1 is the AAR, if present
        FilterKey.setText(new String(msg.getRecords()[0].getPayload()));

        /*Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putString("newfilterkey",new String(msg.getRecords()[0].getPayload()));
        message.setData(bundle);
        message.what = RhybuddHandlers.msg_push_show_undo;
        checkZPHandler.sendMessageDelayed(message,600);*/

    } catch (Exception e) {
        e.printStackTrace();
        BugSenseHandler.sendExceptionMessage("PushSettingsFragment", "processIntent", e);
    }
}

From source file:us.rader.wyfy.MainActivity.java

/**
 * Handle result from {@link WriteTagActivity}
 * /*  ww  w .j a v a 2 s.c o m*/
 * @param resultCode
 *            result code
 * 
 * @param resultData
 *            result data
 */
private void onTagWritten(int resultCode, Intent resultData) {

    switch (resultCode) {

    case RESULT_CANCELED:

        alert(getString(R.string.canceled));
        break;

    case RESULT_OK:

        NdefMessage message = resultData.getParcelableExtra(NdefReaderActivity.EXTRA_RESULT);

        if (message == null) {

            alert(getString(R.string.null_message));

        } else {

            NdefRecord[] records = message.getRecords();

            if ((records == null) || (records.length < 1)) {

                alert(getString(R.string.empty_message));

            } else {

                NdefRecord record = records[0];
                String payload = NdefReaderActivity.decodePayload(record);

                if (payload == null) {

                    alert(getString(R.string.unparseable_payload));

                } else {

                    alert(payload);

                }
            }
        }

        break;

    default:

        alert(getString(R.string.unrecognized_result_code, resultCode));
        break;

    }

}

From source file:com.mario22gmail.license.nfc_project.NavigationDrawerActivity.java

private void readTextFromTag(NdefMessage ndefMessage) {
    NdefRecord[] records = ndefMessage.getRecords();
    if (records != null && records.length > 0) {
        android.nfc.NdefRecord ndefRecord = records[0];
        String tagContent = getTextFromNdefRecord(ndefRecord);
        Log.i(nfcDebugTag, "tag conent from read Text " + tagContent);
        Toast.makeText(this, tagContent, Toast.LENGTH_LONG).show();
    } else {/*from w  w w.  j  a va 2 s  . c  om*/
        Toast.makeText(this, "No Ndef Records", Toast.LENGTH_SHORT).show();
    }
}