Vincent Gélinas Vincent Gélinas - 1 year ago 103
Android Question

How to pass Custom Object through NdefMessage

First question on stackoverflow. I tried to make it clear and up to standards. I am new with Android development and with NFC in particular. I am working on an application where you can create and join event, a little bit like on Facebook. I have a ListEvent activity and a DisplayEvent activity. When I select an event from my list, it open the DisplayEvent activity with the correct information about my event.

I want that when X has Event A open on his device, when he gets in NFC range with Y, Y now has Event A on his device. I am currently able to open the correct activity, and I am even able to send a String from one phone to another. I searched a lot online but I just can't seem to figure out how to send a custom Oject, in my case an Event, through NFC instead of a String. I would also need to send a Boolean along with my Event. It probably is super easy but I'm being stupid on that one. Thank you very much in advance.

Here is my code.

Manifest :

android:value="vincent.ievennement.activity.ListeEventActivity" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" />


protected void onResume() {
//Normal way to get my Event and my Boolean
event = (Event) getIntent().getSerializableExtra("MonEvent");
participe = (boolean) getIntent().getSerializableExtra("Participe");

//I prepare my message and make it ready to be sent when a device is into range
NdefMessage messageSend = createNdefMessage("SomeText");
mNfcAdapter.setNdefPushMessage(messageSend, this);

Intent intent = getIntent();
//If my activity is openned by NFC, proceed to get the message that was sent
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMessages = intent.getParcelableArrayExtra(

NdefMessage message = (NdefMessage) rawMessages[0]; // only one message transferred
Log.e("Test - ",new String(message.getRecords()[0].getPayload()));




public NdefMessage createNdefMessage(String message) {
NdefRecord ndefRecord = NdefRecord.createMime("text/plain", message.getBytes());
NdefMessage ndefMessage = new NdefMessage(ndefRecord);
return ndefMessage;

Answer Source

You can use the NdefRecord.createExternal function to create an NdefRecord containing your application-specific data. The documentation describes how to include a "payload" in an NdefRecord. You'll just need to convert your "custom object" into a byte array which is described here. Then add that to a new NdefRecord and add that to your NdefMessage.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download