-
Notifications
You must be signed in to change notification settings - Fork 13
ExceptionHandling
| Home | Reading NFC Tags | Writing NFC Tags | Creating NdefMessages | Exception Handling |
|---|---|---|---|---|
| How it works | Reading | Writing | NdefMessages | Exceptions |
When executing an NFC write job synchronously, the method's signature clearly shows what will happen when an unexpected situation occurs.
/**
* Write the given message to the tag
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @throws android.nfc.FormatException if the message is in an incorrect format
* @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
* @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
*/
boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException;So, when calling any of the synchronous write methods, you'll have to declare catch clauses which should handle these errors.
Since an exception thrown from another thread is hardly convenient, we chose to implement a callback method onError(Exception e).
AsyncUiCallback mAsyncUiCallback = new AsyncUiCallback() {
@Override
public void callbackWithReturnValue(Boolean result) {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
if (result) {
Toast.makeText(NfcActivity.this, "Write has been done!", Toast.LENGTH_LONG).show();
}
Log.d(TAG,"Received our result : " + result);
}
@Override
public void onProgressUpdate(Boolean... values) {
if (values.length > 0 && values[0] && mProgressDialog != null) {
mProgressDialog.setMessage("Writing");
Log.d(TAG,"Writing !");
}
}
@Override
public void onError(Exception e) {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
Log.i(TAG,"Encountered an error !",e);
Toast.makeText(NfcActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};This method is fired when the AsyncOperationCallback throws any exception, and will just provide the exception as an argument.
You can thus inspect the cause of the error, by examining the message (getMessage()), printing the stacktrace (e.printStacktrace()) or anything else you'd do in a normal catch clause.
Downside is, you'll have to inspect the type of the exception (getClass(), instanceof) in order to set up some bussiness logic.