• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Read tag and then write information into tag without scanning again

toanhoi

Lurker
Oct 10, 2012
2
0
I am writing application to read information from NFC tag after that edit the information and write again to NFC tag without touch second tag (only read and write in the first touch). The data after write into the tag that is displayed into mobile. The processing is such as (Read tag=>Get Information=>Edit information=>Write Tag again=>Read information to display)I found some solution in the internet such as android read back the tag infomation after write, without second touch of tag

But when I implement it.It did not work for writting. This is my edited code (
HTML:
http://www.jessechen.net/blog/how-to-nfc-on-the-android-platform/
). Can you help me?
[HIGH]import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;

public class StickyNotesActivity extends Activity {
private static final String TAG = "stickynotes";
private boolean mResumed = false;
private boolean mWriteMode = false;
NfcAdapter mNfcAdapter;
EditText mNote;
PendingIntent mNfcPendingIntent;
IntentFilter[] mWriteTagFilters;
IntentFilter[] mNdefExchangeFilters;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

setContentView(R.layout.main);
findViewById(R.id.write_tag).setOnClickListener(mTagWriter);
mNote = ((EditText) findViewById(R.id.note));
// mNote.addTextChangedListener(mTextWatcher);

// Handle all of our received NFC intents in this activity.
mNfcPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

// Intent filters for reading a note from a tag or exchanging over p2p.
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefDetected.addDataType("text/plain");
} catch (MalformedMimeTypeException e) { }
mNdefExchangeFilters = new IntentFilter[] { ndefDetected };

// Intent filters for writing to a tag
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
mWriteTagFilters = new IntentFilter[] { tagDetected };
}

@Override
protected void onResume() {
super.onResume();
mResumed = true;

// Sticky notes received from Android
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
//Read mode
NdefMessage[] messages = getNdefMessages(getIntent());
byte[] payload = messages[0].getRecords()[0].getPayload();
String nfcMess=new String(payload);
//Write mode
disableNdefExchangeMode();
enableTagWriteMode();
mNote.setText(nfcMess+"Test");
Tag detectedTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeTag(getNoteAsNdef(), detectedTag);
//Display again
enableNdefExchangeMode();
disableTagWriteMode();
messages = getNdefMessages(getIntent());
payload = messages[0].getRecords()[0].getPayload();
setNoteBody(new String(payload));
}
enableNdefExchangeMode();
}

@Override
protected void onPause() {
super.onPause();
mResumed = false;
mNfcAdapter.disableForegroundNdefPush(this);
}

@Override
protected void onNewIntent(Intent intent) {
// NDEF exchange mode
if (!mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] msgs = getNdefMessages(intent);
String body = new String(msgs[0].getRecords()[0].getPayload());
setNoteBody(body);
}
// Tag writing mode
if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeTag(getNoteAsNdef(), detectedTag);
}
}

private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable arg0) {
if (mResumed) {
mNfcAdapter.enableForegroundNdefPush(StickyNotesActivity.this, getNoteAsNdef());
}
}
};
private View.OnClickListener mTagWriter = new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Write to a tag for as long as the dialog is shown.
disableNdefExchangeMode();
enableTagWriteMode();
}
};
private void setNoteBody(String body) {
Editable text = mNote.getText();
text.clear();
text.append(body);
}
private NdefMessage getNoteAsNdef() {
byte[] textBytes = mNote.getText().toString().getBytes();
NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),
new byte[] {}, textBytes);
return new NdefMessage(new NdefRecord[] {
textRecord
});
}

NdefMessage[] getNdefMessages(Intent intent) {
// Parse the intent
NdefMessage[] msgs = null;
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs = (NdefMessage) rawMsgs;
}
} else {
// Unknown tag type
byte[] empty = new byte[] {};
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
NdefMessage msg = new NdefMessage(new NdefRecord[] {
record
});
msgs = new NdefMessage[] {
msg
};
}
} else {
Log.d(TAG, "Unknown intent.");
finish();
}
return msgs;
}

private void enableNdefExchangeMode() {
mNfcAdapter.enableForegroundNdefPush(StickyNotesActivity.this, getNoteAsNdef());
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mNdefExchangeFilters, null);
}

private void disableNdefExchangeMode() {
mNfcAdapter.disableForegroundNdefPush(this);
mNfcAdapter.disableForegroundDispatch(this);
}

private void enableTagWriteMode() {
mWriteMode = true;
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
mWriteTagFilters = new IntentFilter[] {
tagDetected
};
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null);
}

private void disableTagWriteMode() {
mWriteMode = false;
mNfcAdapter.disableForegroundDispatch(this);
}

boolean writeTag(NdefMessage message, Tag tag) {
int size = message.toByteArray().length;

try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();

if (!ndef.isWritable()) {
toast("Tag is read-only.");
return false;
}
if (ndef.getMaxSize() < size) {
toast("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size
+ " bytes.");
return false;
}

ndef.writeNdefMessage(message);
toast("Wrote message to pre-formatted tag.");
return true;
} else {
NdefFormatable format = NdefFormatable.get(tag);
if (format != null) {
try {
format.connect();
format.format(message);
toast("Formatted tag and wrote message");
return true;
} catch (IOException e) {
toast("Failed to format tag.");
return false;
}
} else {
toast("Tag doesn't support NDEF.");
return false;
}
}
} catch (Exception e) {
toast("Failed to write tag");
}

return false;
}

private void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}[/HIGH]
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones