Skip to main content

NFC- Writing and Reading Mutiple Records at a time

I'm writting this article to help an android developers who is working in NFC and getting confused on how to  write multiple records and how to read them at a go .

 
         I want you to do the following steps ...

copy the following xml into your layout/yourfile



    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TableLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true" >

            <TableRow
               
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <TextView
                 
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:layout_marginLeft="90dp"
                    android:typeface="serif"/>
            </TableRow>

            <TableRow
               
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <TextView
                 
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="90dp"
                    android:text="New Connection "
                    android:typeface="serif" />

            </TableRow>

            <TableRow
               
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <TextView

                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Name"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newconnection_usrname_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    >

                    <requestFocus />
                </EditText>

            </TableRow>
 <TableRow
           
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
               
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="E-mail Id"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newconnection_customerId_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
   
             <TableRow
           
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
               
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Package"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newconnection_package_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
            <TableRow
               
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
               
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Mobile Number"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newconnection_mobile_num_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
        <TableRow
           
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
             
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="E-mail"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newconnection_email_id_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
             <TableRow
             
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
                 
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Address1"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newcoxn_address1_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
           
               <TableRow
             
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
                 
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Address2"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newcoxn_address2_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
              <TableRow
             
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
                 
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="city"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newcoxn_city_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
             
                <TableRow
             
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
                 
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="State"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newcoxn_state_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
                <TableRow
             
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
                 
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Zip"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newcoxn_zip_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>
             
              <TableRow
           
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
              <TextView
               
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Matital Status"
                    android:layout_weight="1"/>

                <EditText
                    android:id="@+id/newconnection_connectioncreated_content"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ems="10"
                   >

                    <requestFocus />
                </EditText>
               
            </TableRow>

                 
           
             <Button
                 android:id="@+id/writetag"
                 android:layout_width="100dp"
                 android:layout_height="wrap_content"
                 android:text="Write Tag" />

             <Button
                 android:id="@+id/button2"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:text="Upload to server" />

             <Button
                 android:id="@+id/button3"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:text="Pending datas" />

             <Button
                 android:id="@+id/canceldialogbutton"
                 android:layout_width="50dp"
                 android:layout_height="wrap_content"
                 android:text="cancel Dialog" />

            </TableLayout>

    </RelativeLayout>



NFCAndroid.java


 package rakesh.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
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 NFCAndroid extends Activity {
   private static final String TAG = "rakesh android";
    private boolean mResumed = false;
    private boolean mWriteMode = false;
    NfcAdapter mNfcAdapter;
    EditText mNote,mnote1,mnote2,mnote3,mnote4,mnote5,mnote6,mnote7,mnote8,mnote9,mnote10;

    PendingIntent mNfcPendingIntent;
    IntentFilter[] mWriteTagFilters;
    IntentFilter[] mNdefExchangeFilters;
    byte[] payload5,payload1,payload2,payload3,payload4,payload6,payload7,payload8,payload9,payload10,payload11;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

        setContentView(R.layout.newconnection);
        findViewById(R.id.writetag).setOnClickListener(mTagWriter);
        mNote = ((EditText) findViewById(R.id.newconnection_usrname_content));
        mnote1 = ((EditText) findViewById(R.id.newconnection_customerId_content));
        mnote2 = ((EditText) findViewById(R.id.newconnection_package_content));
        mnote3 = ((EditText) findViewById(R.id.newconnection_mobile_num_content));
        mnote4 = ((EditText) findViewById(R.id.newconnection_email_id_content));
        mnote5 = ((EditText) findViewById(R.id.newcoxn_address1_content));
        mnote6 = ((EditText) findViewById(R.id.newcoxn_address2_content));
        mnote7 = ((EditText) findViewById(R.id.newcoxn_city_content));
        mnote8 = ((EditText) findViewById(R.id.newcoxn_state_content));
        mnote9 = ((EditText) findViewById(R.id.newcoxn_zip_content));
        mnote10 = ((EditText) findViewById(R.id.newconnection_connectioncreated_content));
       
       
       
        mNote.addTextChangedListener(mTextWatcher);
        mnote1.addTextChangedListener(mTextWatcher);
        mnote2.addTextChangedListener(mTextWatcher);
        mnote3.addTextChangedListener(mTextWatcher);
        mnote4.addTextChangedListener(mTextWatcher);
        mnote5.addTextChangedListener(mTextWatcher);
        mnote6.addTextChangedListener(mTextWatcher);
        mnote7.addTextChangedListener(mTextWatcher);
        mnote8.addTextChangedListener(mTextWatcher);
        mnote9.addTextChangedListener(mTextWatcher);
        mnote10.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())) {
           
       
        NdefMessage[] msgs = getNdefMessages(getIntent());
            NdefRecord[] ndefRecords = msgs[0].getRecords();
            int totalRecords = ndefRecords.length;
            if(totalRecords == 11)
            {
                NdefRecord ndefRecord1 = msgs[0].getRecords()[0];
                NdefRecord ndefRecord2 = msgs[0].getRecords()[1];
                NdefRecord ndefRecord3 = msgs[0].getRecords()[2];
                NdefRecord ndefRecord4 = msgs[0].getRecords()[3];
                NdefRecord ndefRecord5 = msgs[0].getRecords()[4];
                NdefRecord ndefRecord6 = msgs[0].getRecords()[5];
                NdefRecord ndefRecord7 = msgs[0].getRecords()[6];
                NdefRecord ndefRecord8 = msgs[0].getRecords()[7];
                NdefRecord ndefRecord9 = msgs[0].getRecords()[8];
                NdefRecord ndefRecord10 = msgs[0].getRecords()[9];
                NdefRecord ndefRecord11 = msgs[0].getRecords()[10];
               
                payload1 = ndefRecord1.getPayload();
                payload2 = ndefRecord2.getPayload();
                payload3 = ndefRecord3.getPayload();
                payload4 = ndefRecord4.getPayload();
                payload5 = ndefRecord5.getPayload();
                payload6 = ndefRecord6.getPayload();
                payload7 = ndefRecord7.getPayload();
                payload8 = ndefRecord8.getPayload();
                payload9 = ndefRecord9.getPayload();
                payload10 = ndefRecord10.getPayload();
                payload11 = ndefRecord11.getPayload();
             
       
            }
       
        /*
        NdefMessage[] messages = getNdefMessages(getIntent());
            payload = messages[0].getRecords()[0].getPayload();
            payload1 = messages[0].getRecords()[1].getPayload();
            payload2 = messages[1].getRecords()[0].getPayload();
            payload3 = messages[1].getRecords()[1].getPayload();
            payload4 = messages[0].getRecords()[4].getPayload();*/
         
            setNoteBody(new String(payload1),new String(payload2),new String(payload3),new String(payload4),new String(payload5),new String(payload6),new String(payload7),new String(payload8),new String(payload9),new String(payload10),new String(payload11));
            setIntent(new Intent()); // Consume this intent.
        }
        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);
            promptForContent(msgs);
           
        }

        // 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(NFCAndroid.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();

            new AlertDialog.Builder(NFCAndroid.this).setTitle("Touch tag to write")
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            disableTagWriteMode();
                           
                            enableNdefExchangeMode();
                        }
                    }).create().show();
        }
    };

    private void promptForContent(final NdefMessage[] msg) {
        new AlertDialog.Builder(this).setTitle("Replace current content?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
               
                NdefRecord firstRecord = msg[0].getRecords()[0];
                String body = new String(firstRecord.getPayload());
               
               
                NdefRecord firstRecord1 = msg[0].getRecords()[1];
                  String body1 = new String(firstRecord1.getPayload());
                 
                 
                  NdefRecord firstRecord2= msg[0].getRecords()[2];
                  String body2 = new String(firstRecord2.getPayload());
                 
                 
                  NdefRecord firstRecord3 = msg[0].getRecords()[3];
                  String body3 = new String(firstRecord3.getPayload());
                 
                 
                  NdefRecord firstRecord4 = msg[0].getRecords()[4];
                  String body4 = new String(firstRecord4.getPayload());
                 
                 
                  NdefRecord firstRecord5 = msg[0].getRecords()[5];
                  String body5 = new String(firstRecord5.getPayload());
                 
                 
                  NdefRecord firstRecord6 = msg[0].getRecords()[6];
                  String body6 = new String(firstRecord6.getPayload());
                 
                 
                  NdefRecord firstRecord7 = msg[0].getRecords()[7];
                  String body7 = new String(firstRecord7.getPayload());
                 
                 
                  NdefRecord firstRecord8 = msg[0].getRecords()[8];
                  String body8 = new String(firstRecord8.getPayload());
                 
                 
                  NdefRecord firstRecord9 = msg[0].getRecords()[9];
                  String body9 = new String(firstRecord9.getPayload());
                 
                  NdefRecord firstRecord10 = msg[0].getRecords()[10];
                  String body10 = new String(firstRecord10.getPayload());
                 
                   
                   
                 
                 
                  setNoteBody(body,body1,body2,body3,body4,body5,body6,body7,body8,body9,body10);
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
               
               
               
               
               
             
               
               
                }
            }).show();
    }

    private void setNoteBody(String body,String body1,String body2,String body3,String body4,String body5,String body6,String body7,String body8,String body9,String body10) {
     
   
    Editable text = mNote.getText();
        text.clear();
        text.append(body);
       
       
        Editable text1 = mnote1.getText();
        text1.clear();
        text1.append(body1);
       
       
        Editable text2 = mnote2.getText();
        text2.clear();
        text2.append(body2);
       
     
        Editable text3 = mnote3.getText();
        text3.clear();
        text3.append(body3);
       
       
        Editable text4 = mnote4.getText();
        text4.clear();
        text4.append(body4);
     
        Editable text5 = mnote5.getText();
        text5.clear();
        text5.append(body5);
   
        Editable text6 = mnote6.getText();
        text6.clear();
        text6.append(body6);
     

        Editable text7 = mnote7.getText();
        text7.clear();
        text7.append(body7);
   

        Editable text8 = mnote8.getText();
        text8.clear();
        text8.append(body8);
   
        Editable text9 = mnote9.getText();
        text9.clear();
        text9.append(body9);
 
        Editable text10 = mnote10.getText();
        text10.clear();
        text10.append(body10);
   
   
   
    }

    private NdefMessage getNoteAsNdef() {
     
   
    byte[] textBytes=mNote.getText().toString().getBytes(); ;
        NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),  new byte[] {}, textBytes);
             
       
        byte[] textBytes1=mnote1.getText().toString().getBytes(); ;
        NdefRecord textRecord1 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(), new byte[] {}, textBytes1);
       
       
        byte[] textBytes2=mnote2.getText().toString().getBytes(); ;
        NdefRecord textRecord2= new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),new byte[] {}, textBytes2);      
       
       
        byte[] textBytes3=mnote3.getText().toString().getBytes(); ;
        NdefRecord textRecord3 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(), new byte[] {}, textBytes3);
       
        byte[] textBytes4=mnote4.getText().toString().getBytes(); ;
        NdefRecord textRecord4 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),new byte[] {}, textBytes4);
       
        byte[] textBytes5=mnote5.getText().toString().getBytes(); ;
        NdefRecord textRecord5 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),new byte[] {}, textBytes5);
       
        byte[] textBytes6=mnote6.getText().toString().getBytes(); ;
        NdefRecord textRecord6 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),new byte[] {}, textBytes6);
     
        byte[] textBytes7=mnote7.getText().toString().getBytes(); ;
        NdefRecord textRecord7 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),new byte[] {}, textBytes7);
       
        byte[] textBytes8=mnote8.getText().toString().getBytes(); ;
        NdefRecord textRecord8 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),new byte[] {}, textBytes8);
       
        byte[] textBytes9=mnote9.getText().toString().getBytes(); ;
        NdefRecord textRecord9 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),new byte[] {}, textBytes9);
       
        byte[] textBytes10=mnote10.getText().toString().getBytes(); ;
        NdefRecord textRecord10 = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),new byte[] {}, textBytes10);
     
        return new NdefMessage(new NdefRecord[] { textRecord,textRecord1,textRecord2,textRecord3,textRecord4,textRecord5,textRecord6,textRecord7,textRecord8,textRecord9,textRecord10});
             
           
        }      
       

    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[i] = (NdefMessage) rawMsgs[i];
                }
            } 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(NFCAndroid.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();
    }
}



AndroidManifest.xml



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="rakesh.android"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.NFC"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="rakesh.android.NFCAndroid"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <!-- Handle notes detected from outside our application -->
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>
        </activity>

    </application>
</manifest>


Note :you have to open directly to write the tag. and open using NFC tag to read the Tag


Comments

Popular posts from this blog

Circular Seek Bar - Example

MyView.java package com.rakesh.androidcircularseekbar; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class MyView extends View {     /** The context */     private Context mContext;     /** The listener to listen for changes */     private OnSeekChangeListener mListener;     /** The color of the progress ring */     private Paint circleColor;     /** the color of the inside circle. Acts as background color */     private Paint innerColor;     /** The progress circle ring background */     private Paint circleRing;   ...

SSL pinning in Android - A brief discussion

HTTP protocol Communication between the client and a server typically non-encrypted or plain text while we use HTTP protocol.  Pitfall Any middle hacker can interrupt the connection between the client and server and manipulate the data as it involves no encryption. How to overcome this ? As the domain owner one can purchase a digital certificate from CA(Certificate Authority) who are considered as trusted.  A certificate will contain the Owner's name, public key , Issuer's(CA's) name,Issuer's(CA's) signature, domain details, expiry date etc . After the SSL/Leaf certificate is associated with a domain,the communication between client and server will be encrypted. Now the HTTP will become HTTPs. Note : Associating the SSL certificate means it enable the encryption between client and server but does not mean ,the domain owner will never misuse your personal information. How does SSL work ? Pitfall There is a problem here. Let's assume that there is a hacker comes i...

Android - Activity Life cycle

The android activity provides 7 call backs which will be invoked based on the states of the activity For better undersatnding,The Activity A and Activity B with the all the call backs overridden. ActivityA :  public class ActivityA extends Activity {     @Override    protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         Log.e("A-OnCreate", "Object Creation");     }     public void next(View v) {         Intent i = new Intent(this, Main2Activity.class);         startActivity(i);     }     @Override    protected void onStart() {         super.onStart();         Log.e("A-onStart", "View is visible but will not be able to interact");     } ...