Similar question - How to read detected NFC tag (NDEF content) details in android?
I want my android app to be able to read and parse a detected NDEF message.
I have already edited the AndroidManifest.xml to detect nfc tags and I have added the intent filter it looks like this
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
I believe this is fine as when I use the NFCDemo sample app that comes with the SDK to create MockNDEFtags, when the list of applications I can choose to handle these generated tags my app appears. I then click on my app and it opens up without problem, I just need a way to read the data that was passed to it in the NDEF message. The code:
Tag myTag = (Tag) nfcintent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// get NDEF tag details
Ndef ndefTag = Ndef.get(myTag);
...
NdefMessage ndefMesg = ndefTag.getCachedNdefMessage();
was suggested in a similar question and throughout the web I find many similar answers. My problem is with the line of code
"Tag myTag = (Tag) nfcintent.getParcelableExtra(NfcAdapter.EXTRA_TAG);"
I get the error "nfcintent cannot be resolved" I realize that the author of the code likely put nfcintent as a placeholder for an intent specific to my app however im not sure what im supposed to put in its place.
My mainactivity that starts my app looks like this
public class TabsActivity extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabHost = getTabHost();
// Tab for Graph
TabSpec graphspec = tabHost.newTabSpec("Graph");
// setting Title and Icon for the Tab
graphspec.setIndicator("Graph");
Intent graphIntent = new Intent(this, GraphActivity.class);
graphspec.setContent(graphIntent);
// Tab for Intro
TabSpec introspec = tabHost.newTabSpec("Intro");
introspec.setIndicator("Intro");
Intent introIntent = new Intent(this, IntroActivity.class);
introspec.setContent(introIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(introspec); // Adding intro tab
tabHost.addTab(graphspec); // Adding graph tab
}
}
I assume as this starts the app it is where the NFC tag must be dealt with. If I can just access the NDEFMessage from the tag I already have the ability to parse it with the NdefMessageParser from the android sample app. I want to parse the information from the NDEFmessage and ultimately have that information accessible by each tab in the app.
Try this Snippet to extract message from Tag :
Parcelable[] rawMsgs = intent
.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
extractMessage(msg);
private void extractMessage(NdefMessage msg) {
byte[] array = null;
array = msg.getRecords()[0].getPayload();
}
Also Check out this Sample for NFC Reader/Writer