Monday, January 28, 2013

NFC Android Tutorial

Overview

NFC (Near Field Communication) is set of standards that enable smartphones and similar devices to establish a radio communication*( requires a distance of 4cm or less to initiate a connection) and allows to transfer data such as text or numbers between two NFC enabled devices.
In practice, NFC enables simple and safe two- way interactions among electronic devices within a close proximity
NFC standards are  based on RFID (radio frequency identification) standards.

NFC

Device should be NFC enabled to use this technology


Nfc Features
•  Short range technology
                  –  Connection established when devices or tag close enough (5-10 cm)
                  –  Simple setup (instant configuration)
•  2-way communication
                  –  Not only reading like in contactless smart cards, but data exchange
•  Passive tags
                  –  No need for external power
                  –  Low-price
•  Security
                  –  Support secure element
                  –  Close proximity use brings some basic security
What  can we store in NFC tags?

We can store variety of data on NFC TAG. The actual amount of data varies depending on the type of NFC tag used - different tags have different memory capacities.  A standard Ultralight nfc tag can  store a URL of around 41 characters, while NTAG203   can store data around 132 characters.
Usually, this information is stored in a specific data format (NDEF - NFC data exchange format) so that it can be reliably read by most devices and mobile phones.

Nfc Modes

•  Read and write tags
•  Peer-to-peer
•  Card emulation

Android Support
          –  Read and write (excellent support)
P2P (limited)

Requirements for using NFC enabled application

Most Important requirement for a device is that it should have required hardware to support NFC feature
here is the list of NFC enabled mobile devices

Minimum API required

API level 9 only supports limited tag dispatch via Action_Tag_Discovered and only gives access to NDEF messages via the EXTRA_NDEF_MESSAGE extra. No other tag properties or I/O operations are accessible. API level 10 includes comprehensive reader/writer support as well as foreground NDEF pushing, and API level 14 provides an easier way to push NDEF messages to other devices with Android Beam and extra convenience methods to create NDEF records.

Permissions required for Android application to use NFC

<uses-permission android:name="android.permission.NFC" />

<uses-sdk android:minSdkVersion="10"/>

<uses-feature android:name="android.hardware.nfc" android:required="true" />

Key Players

NfcManager  is the high level manager, used to obtain this device's NfcAdapter.
NfcAdapter  represents the device's NFC adapter, which is your entry-point to performing NFC operations
NdefMessage Represents NDEF data message, which is the standard format in which "records" carrying data are transmitted between devices and tags. Your application can receive these messages from ACTION_TAG_DISCOVERED ntent.
NdefRecord Represents a record, which is delivered in a NdefMessage and describes the type of data being shared and carries the data itself.
How NFC tags are read
Reading NDEF data from an NFC tag is handled with the tag dispatch system , which analyzes discovered NFC tags, appropriately categorizes the data, and starts an application that is interested in the categorized data. An application that wants to handle the scanned NFC tag can declare an intent filter and request to handle the data.

Enabling foreground
/**
* Enables foreground intent detection
*/
    public void enableForeground() {

        if(!foreground) {

            IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
            IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
            writeTagFilters = new IntentFilter[] {tagDetected, ndefDetected};
            nfcAdapter.enableForegroundDispatch(context, nfcPendingIntent, writeTagFilters, null);

            foreground = true;
        }
    }



Now we create a IntentFilter, to tell Android that our application is enabled to work on nfc tag (NfcAdapter.ACTION_TAG_DISCOVERED). We register our app with an intentFilter in the Manifest.

<activity android:name="com.example.activity.NfcReaderActivity" >
            <intent-filter>
                <action android:name="android.nfc.action.TAG_DISCOVERED" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
method to read nfc tag

/**
     * Reads the ndef messages from the given intent
     *
     * @param intent
     * @return true if messages were extracted
     */
    public boolean read(Intent intent) {
        Log.d(TAG, "Read intent");

        Parcelable[] messages = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (messages != null) {
            NdefMessage[] ndefMessages = new NdefMessage[messages.length];
            for (int i = 0; i < messages.length; i++) {
                ndefMessages[i] = (NdefMessage) messages[i];
            }

            if (ndefMessages.length > 0) {
                listener.readNdefMessages(ndefMessages);

                return true;
            } else {
                listener.readNdefEmptyMessage();
            }
        } else {
            listener.readNonNdefMessage();
        }

        return false;
    }
­
Writing NFC tags
­
    public boolean write(final NdefMessage message, Intent intent) {
        final Tag extra = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Thread t = new Thread(new Runnable() {
            Tag tag = extra;

            @Override
            public void run() {
        NdefFormatable format = NdefFormatable.get(tag);
        if (format != null) {
            Log.d(TAG, "Write unformatted tag");
            try {
                format.connect();
                format.format(message);

                listener.wroteNdefUnformatted();

                        return;
            } catch (Exception e) {
                listener.writeNdefUnformattedFailed(e);
            }
                    finally{
                        try {
                            format.close();
                        } catch (IOException e) {
                            Log.d(TAG, "Cannot close connection to the tag.");
                        }
                    }
            Log.d(TAG, "Cannot write unformatted tag");
        } else {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                try {
                    Log.d(TAG, "Write formatted tag");

                    ndef.connect();
                    if (!ndef.isWritable()) {
                        Log.d(TAG, "Tag is not writeable");

                        listener.writeNdefNotWritable();

                                return;
                    }
                    if (ndef.getMaxSize() < message.toByteArray().length) {
                        Log.d(TAG,
                                "Tag size is too small, have "
                                        + ndef.getMaxSize() + ", need "
                                        + message.toByteArray().length);

                        listener.writeNdefTooSmall(
                                message.toByteArray().length, ndef.getMaxSize());

                                return;
                    }
                    ndef.writeNdefMessage(message);

                    listener.wroteNdefFormatted();

                            return;
                } catch (Exception e) {
                    listener.writeNdefFormattedFailed(e);
                }
            } else {
                listener.writeNdefCannotWriteTech();
            }
            Log.d(TAG, "Cannot write formatted tag");
        }

            }
        });

        t.run();
        return success;
    }

Sources:
 download the nfctools.jar file from here

ORMLite Android Tutorial

ORMLite provides a lightweight Object Relation Mapping between Java classes and SQL databases.

OVERVIEW

ORMLite provides a lightweight Object Relation Mapping between Java classes and SQL databases ORMLite supports JDBC connections to MySQL, Postgres, H2, SQLite, Derby, HSQLDB, Microsoft SQL Server. ORMLite also supports native database calls on Android Operating System.

Implementatin ORMLite with Android

To get started with ORMLite, We need to download the ORMLite jar files.These can be downloaded from ORMLite release page
Once we download ORMLite we need to add external library to our android project. Put the jar file into your project’s libs/ subdirectory.
We only need the ormlite-android-4.14.jar, not the ormlite-core or any other packages.
Getting Started with  ORMLite
Get started Ormlite we will need to create our own database helper class which should extend the OrmLiteSqliteOpenHelper class. This class creates and upgrades the database when the application is installed and also provide the DAO(Data Access Object) classes used by other classes. The helper class must implement the methods
onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)
onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)
onCreate creates the database when app is first installed while onUpgrade handles the upgrading of the database tables when we upgrade our app to a new version.
The helper should be kept open across all activities in the app with the same SQLite database connection reused by all threads. If we open multiple connections to the same database, stale data and unexpected results may occur. It is recommended to use the OpenHelperManager to monitor the usage of the helper – it will create it on the first access, track each time a part of our code is using it, and then it will close the last time the helper is released.
Once we define our database helper and are managing it correctly, We will use it in our Activity classes. An easy way to use the OpenHelperManager is to extend OrmLiteBaseActivity for each of your activity classes – there is also OrmLiteBaseListActivity, OrmLiteBaseService, and OrmLiteBaseTabActivity. These classes provide a helper protected field and a getHelper() method to access the database helper whenever it is needed and will automatically create the helper in the onCreate() method and release it in the onDestroy() method.


Sample Database Helper 


import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
/**
* Database helper class used to manage the creation and upgrading of your
* database. This class also usually provides the DAOs used by the other classes.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application — change to something appropriate for your app
private static final String DATABASE_NAME = “scotchadmins”;
// any time you make changes to your database, you may have to increase the database version
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the any table
private Dao<DemoORMLite, Integer> DemoORMLiteDao = null;
private RuntimeExceptionDao<DemoORMLite, Integer> DemoORMLiteRuntimeDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* This is called when the database is first created. Usually you should
* call createTable statements here to create the tables that will store your data.
*/
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), “onCreate”);
TableUtils.createTable(connectionSource, DemoORMLite.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), “Can’t create database”, e);
throw new RuntimeException(e);
}
// here we try inserting data in the on-create as a test
RuntimeExceptionDao<DemoORMLite, Integer> dao = getDemoORMLiteDao();
String name = scotchadmins
// create some entries in the onCreate
long date = System.currentTimeMillis();
DemoORMLite demo = new DemoORMLite(name,date);
dao.create(demo);
Log.i(DatabaseHelper.class.getName(), “created new entries in onCreate: “);
}
/**
* This is called when the application is upgraded and it has a higher
* version number. This allows you to adjust the various data to match the
* new version number.
*/
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), “onUpgrade”);
TableUtils.dropTable(connectionSource, DemoORMLite.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), “Can’t drop databases”, e);
throw new RuntimeException(e);
}
}
/**
* Returns the Database Access Object (DAO) for our SimpleData class. It
* will create it or just give the cached value.
*/
public Dao<DemoORMLite, Integer> getDao() throws SQLException {
if (DemoORMLiteDao == null) {
DemoORMLiteDao = getDao(DemoORMLite.class);
}
return DemoORMLiteDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
DemoORMLiteRuntimeDao = null;
}
}

Creating a Table in ORMLite


There are a few things to notice when we use ORMLite
First: We just annotate our class as a table and its members as fields and we’ re almost done with creating a table
The second thing to notice is that ORMLite handles all of the basic data types without any explicit work on your part (integers, strings, floats, dates, and more).

It is mandatory to have a no argument constructor in our class

public class DemoORMLite {
// Class name will be tablename Fields here
@DatabaseField(generatedId = true, canBeNull = false)
int _id;
@DatabaseField(canBeNull = true)
String first_name;
@DatabaseField(canBeNull = true)
String last_name;
@DatabaseField(canBeNull = true)
Date created;
DemoORMLite() {
}

public DemoORMLite(String name,long date) {
this.first_name = name;
this.last_name = “lastname”;
this.created = new Date(date);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(_id);
sb.append(“, “).append(first_name);
sb.append(“, “).append(last_name);
SimpleDateFormat dateFormatter = new SimpleDateFormat(
“MM/dd/yyyy HH:mm:ss.S”);
sb.append(“, “).append(dateFormatter.format(created));
return sb.toString();
}
}
}

Database Operations

Deleting a record in ormlite
DeleteBuilder assists in building sql DELETE statements for a particular table in a  database.
Sample Code that  deletes elements from table in field by arg
DatabaseHelper helper = OpenHelperManager.getHelper(App.getContext(), DatabaseHelper.class);
Dao dao = helper.getDao(YOUR_CLASS.class);
DeleteBuilder<CanteenLog, Integer> deleteBuilder = dao.deleteBuilder();
deleteBuilder.where().eq(“FIELD_NAME”, arg);
deleteBuilder.delete();

Query in ORMLite

1.Query for all
returns the list of all records in the table we have inbuild function queryForAll();
// get our dao
RuntimeExceptionDao<DemoORMLite, Integer> DemoORMLiteDao = getHelper().getDemoORMLiteDao ();
// query for all of the data objects in the database
List<SimpleData> list = simpleDao.queryForAll();
2.Query for id
returns the record corresponding to given id we have inbuild function queryForId(id);
Sample code
TEntity entity = this.dao.queryForId(id)
3.Query for particular field name
here we query for field “lastname” and it returns list of records that have last_name =”lastname”

public List<DemoORMLite> RetrieveByLastName(String lastname)  throws SQLException {
QueryBuilder<TEntity, Integer> queryBuilder = dao.queryBuilder();
List<TEntity> list;
queryBuilder.where().eq(“last_name”, lastname);
list = queryBuilder.query();
return list;
}