Reading From a NFC Tag

Peter-John Welcome
AndroidPub
Published in
2 min readSep 3, 2017
https://advicesacademy.com/wp-content/uploads/2015/02/NFC-on-Android.png

In my previous post, I spoke about how we can write data to an NFC tag from our Android devices.

In this post, I’ll be showing how we can get that information back into our Android app, so we will be continuing from where we left off in the NFC app.

Getting Started

First, we will need to create a method called retrieveNFCMessage that takes an Intent as an argument and returns a String. We will need to check if the action of the Intent, that gets passed to this method, is an ACTION_NDF_DISCOVERED action. If so, we will pass the Intent to a method called getNDefMessages which we will create.

Our getNDefMessages will also take an Intent as an argument and return it as an array of NDefMessage. At this point, we will get the raw messages from the Intent, iterate through the messages and cast each message to the NDefMessage object. We will then return that array.

If our raw messages from the Intent are null we just create an empty NDefMessage and return that within an array.

Back to our retrieveNFCMessage method. We will look at the first object in the array and check its NdefRecord’s. If that is not null, we iterate through the records, checking if it has any payloads, and if it does, we take that payload which is an array of bytes and create a String from it. This is then the String we return from this method.

We have gotten to a point where we can test and see if this works.

We write our message to the NFC Tag.

Then we read it from the NFC Tag.

Yaye =). It works.

I hope this is helpful to peeps out there. If you have any questions, leave some comments below.

Happy NFC’ing.

PS: If you having issues with the NFC Tag not reading, make sure you have your scheme set to vnd.android.nfc in your Manifest.

android:scheme=”vnd.android.nfc”

For a more complete example of the code above, you can visit my Github page:

https://github.com/pjwelcome/NFC_Android_Tutorial

Get in Touch!

Peter John Welcome — Google+

Thanks to Ashton Welcome and Joshua Leibstein for reviewing this post.

--

--

Peter-John Welcome
AndroidPub

Freelance Senior Mobile Engineer, Google Developer Expert for Firebase, Photographer