Merge "Use LOCAL_REQUIRED_MODULES instead of LOCAL_JNI_SHARED_LIBRARIES"
diff --git a/nci/jni/Android.mk b/nci/jni/Android.mk
index 39832fd..d2f718b 100644
--- a/nci/jni/Android.mk
+++ b/nci/jni/Android.mk
@@ -10,6 +10,8 @@
 LOCAL_CFLAGS += -DNCI_VERSION=$(NCI_VERSION) -O0 -g
 endif
 
+LOCAL_CFLAGS += -Wall -Wextra
+
 define all-cpp-files-under
 $(patsubst ./%,%, \
   $(shell cd $(LOCAL_PATH) ; \
@@ -26,6 +28,7 @@
     external/libxml2/include \
     external/icu4c/common \
     frameworks/native/include \
+    libcore/include \
     $(NFA)/include \
     $(NFA)/brcm \
     $(NFC)/include \
@@ -51,4 +54,3 @@
 LOCAL_MODULE_TAGS := optional
 
 include $(BUILD_SHARED_LIBRARY)
-
diff --git a/nci/jni/IntervalTimer.cpp b/nci/jni/IntervalTimer.cpp
index f71ca8e..9453451 100644
--- a/nci/jni/IntervalTimer.cpp
+++ b/nci/jni/IntervalTimer.cpp
@@ -24,14 +24,14 @@
 
 IntervalTimer::IntervalTimer()
 {
-    mTimerId = NULL;
+    mTimerId = 0;
     mCb = NULL;
 }
 
 
 bool IntervalTimer::set(int ms, TIMER_FUNC cb)
 {
-    if (mTimerId == NULL)
+    if (mTimerId == 0)
     {
         if (cb == NULL)
             return false;
@@ -69,11 +69,11 @@
 
 void IntervalTimer::kill()
 {
-    if (mTimerId == NULL)
+    if (mTimerId == 0)
         return;
 
     timer_delete(mTimerId);
-    mTimerId = NULL;
+    mTimerId = 0;
     mCb = NULL;
 }
 
diff --git a/nci/jni/NativeLlcpConnectionlessSocket.cpp b/nci/jni/NativeLlcpConnectionlessSocket.cpp
index ecc57e3..99a4b22 100644
--- a/nci/jni/NativeLlcpConnectionlessSocket.cpp
+++ b/nci/jni/NativeLlcpConnectionlessSocket.cpp
@@ -19,6 +19,8 @@
 #include "OverrideLog.h"
 #include "NfcJniUtil.h"
 #include "JavaClassConstants.h"
+#include <ScopedLocalRef.h>
+#include <ScopedPrimitiveArray.h>
 extern "C"
 {
     #include "nfa_api.h"
@@ -57,29 +59,25 @@
 *******************************************************************************/
 static jboolean nativeLlcpConnectionlessSocket_doSendTo (JNIEnv *e, jobject o, jint nsap, jbyteArray data)
 {
-    tNFA_STATUS status = NFA_STATUS_FAILED;
-    jint handle = 0;
-    uint8_t* buf = NULL;
-    uint32_t len = 0;
-    jclass c = NULL;
-    jfieldID f = NULL;
-
     ALOGD ("%s: nsap = %d", __FUNCTION__, nsap);
 
-    c = e->GetObjectClass (o);
-    f = e->GetFieldID (c, "mHandle", "I");
-    handle = e->GetIntField (o, f);
+    ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+    jfieldID f = e->GetFieldID(c.get(), "mHandle", "I");
+    jint handle = e->GetIntField(o, f);
 
-    buf = (uint8_t*) e->GetByteArrayElements (data, NULL);
-    len = (uint32_t) e->GetArrayLength (data);
+    ScopedByteArrayRO bytes(e, data);
+    if (bytes.get() == NULL) {
+        return JNI_FALSE;
+    }
+    size_t byte_count = bytes.size();
 
-    ALOGD ("NFA_P2pSendUI: len = %d", len);
-    status = NFA_P2pSendUI ((tNFA_HANDLE) handle, nsap, len, buf);
+    ALOGD("NFA_P2pSendUI: len = %d", byte_count);
+    UINT8* raw_ptr = const_cast<UINT8*>(reinterpret_cast<const UINT8*>(&bytes[0])); // TODO: API bug; NFA_P2pSendUI should take const*!
+    tNFA_STATUS status = NFA_P2pSendUI((tNFA_HANDLE) handle, nsap, byte_count, raw_ptr);
 
-    ALOGD ("%s: NFA_P2pSendUI done, status = %d", __FUNCTION__, status);
-    if (status != NFA_STATUS_OK)
-    {
-        ALOGE ("%s: NFA_P2pSendUI failed, status = %d", __FUNCTION__, status);
+    ALOGD("%s: NFA_P2pSendUI done, status = %d", __FUNCTION__, status);
+    if (status != NFA_STATUS_OK) {
+        ALOGE("%s: NFA_P2pSendUI failed, status = %d", __FUNCTION__, status);
         return JNI_FALSE;
     }
     return JNI_TRUE;
@@ -169,14 +167,11 @@
 ** Returns:         LlcpPacket Java object.
 **
 *******************************************************************************/
-static jobject nativeLlcpConnectionlessSocket_doReceiveFrom (JNIEnv *e, jobject o, jint linkMiu)
+static jobject nativeLlcpConnectionlessSocket_doReceiveFrom (JNIEnv* e, jobject, jint linkMiu)
 {
-    jbyteArray receivedData = NULL;
-    jobject llcpPacket = NULL;
-    jclass clsLlcpPacket = NULL;
-    jfieldID f = NULL;
-
     ALOGD ("%s: linkMiu = %d", __FUNCTION__, linkMiu);
+    jobject llcpPacket = NULL;
+    ScopedLocalRef<jclass> clsLlcpPacket(e, NULL);
 
     if (sConnlessRecvWaitingForData != JNI_FALSE)
     {
@@ -216,8 +211,8 @@
     }
 
     // Get NativeConnectionless class object
-    clsLlcpPacket = e->GetObjectClass (llcpPacket);
-    if (e->ExceptionCheck ())
+    clsLlcpPacket.reset(e->GetObjectClass(llcpPacket));
+    if (e->ExceptionCheck())
     {
         e->ExceptionClear();
         ALOGE ("%s: Get Object class error", __FUNCTION__);
@@ -225,17 +220,21 @@
     }
 
     // Set Llcp Packet remote SAP
-    f = e->GetFieldID (clsLlcpPacket, "mRemoteSap", "I");
-    e->SetIntField (llcpPacket, f, (jbyte) sConnlessRecvRemoteSap);
+    jfieldID f;
+    f = e->GetFieldID(clsLlcpPacket.get(), "mRemoteSap", "I");
+    e->SetIntField(llcpPacket, f, (jbyte) sConnlessRecvRemoteSap);
 
     // Set Llcp Packet Buffer
     ALOGD ("%s: Received Llcp packet buffer size = %d\n", __FUNCTION__, sConnlessRecvLen);
-    f = e->GetFieldID (clsLlcpPacket, "mDataBuffer", "[B");
-    receivedData = e->NewByteArray (sConnlessRecvLen);
-    e->SetByteArrayRegion (receivedData, 0, sConnlessRecvLen, (jbyte*) sConnlessRecvBuf);
-    e->SetObjectField (llcpPacket, f, receivedData);
+    f = e->GetFieldID(clsLlcpPacket.get(), "mDataBuffer", "[B");
 
-TheEnd:
+    {
+        ScopedLocalRef<jbyteArray> receivedData(e, e->NewByteArray(sConnlessRecvLen));
+        e->SetByteArrayRegion(receivedData.get(), 0, sConnlessRecvLen, (jbyte*) sConnlessRecvBuf);
+        e->SetObjectField(llcpPacket, f, receivedData.get());
+    }
+
+TheEnd: // TODO: should all the "return connectionlessCleanup()"s in this function jump here instead?
     connectionlessCleanup ();
     if (sem_destroy (&sConnlessRecvSem))
     {
@@ -258,20 +257,14 @@
 *******************************************************************************/
 static jboolean nativeLlcpConnectionlessSocket_doClose (JNIEnv *e, jobject o)
 {
-    tNFA_STATUS status = NFA_STATUS_FAILED;
-    jint handle = 0;
-    jclass c = NULL;
-    jfieldID f = NULL;
-
     ALOGD ("%s", __FUNCTION__);
 
-    c = e->GetObjectClass (o);
-    f = e->GetFieldID (c, "mHandle", "I");
-    handle = e->GetIntField (o, f);
+    ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+    jfieldID f = e->GetFieldID(c.get(), "mHandle", "I");
+    jint handle = e->GetIntField(o, f);
 
-    status = NFA_P2pDisconnect ((tNFA_HANDLE) handle, FALSE);
-    if (status != NFA_STATUS_OK)
-    {
+    tNFA_STATUS status = NFA_P2pDisconnect((tNFA_HANDLE) handle, FALSE);
+    if (status != NFA_STATUS_OK) {
         ALOGE ("%s: disconnect failed, status = %d", __FUNCTION__, status);
         return JNI_FALSE;
     }
diff --git a/nci/jni/NativeLlcpServiceSocket.cpp b/nci/jni/NativeLlcpServiceSocket.cpp
index e1c2bb5..17145ef 100644
--- a/nci/jni/NativeLlcpServiceSocket.cpp
+++ b/nci/jni/NativeLlcpServiceSocket.cpp
@@ -44,7 +44,7 @@
 ** Returns:         LlcpSocket Java object.
 **
 *******************************************************************************/
-static jobject nativeLlcpServiceSocket_doAccept(JNIEnv *e, jobject o, jint miu, jint rw, jint linearBufferLength)
+static jobject nativeLlcpServiceSocket_doAccept(JNIEnv *e, jobject o, jint miu, jint rw, jint /*linearBufferLength*/)
 {
     jobject     clientSocket = NULL;
     jclass      clsNativeLlcpSocket = NULL;
@@ -155,4 +155,3 @@
 
 
 } //namespace android
-
diff --git a/nci/jni/NativeLlcpSocket.cpp b/nci/jni/NativeLlcpSocket.cpp
index 74a59b9..ad03506 100644
--- a/nci/jni/NativeLlcpSocket.cpp
+++ b/nci/jni/NativeLlcpSocket.cpp
@@ -16,6 +16,8 @@
 #include "OverrideLog.h"
 #include "PeerToPeer.h"
 #include "JavaClassConstants.h"
+#include <ScopedPrimitiveArray.h>
+#include <ScopedUtfChars.h>
 
 
 namespace android
@@ -36,20 +38,13 @@
 *******************************************************************************/
 static jboolean nativeLlcpSocket_doConnect (JNIEnv* e, jobject o, jint nSap)
 {
-    bool            stat = false;
-    jboolean        retVal = JNI_FALSE;
-
     ALOGD ("%s: enter; sap=%d", __FUNCTION__, nSap);
 
-    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle (e,o);
-
-    stat = PeerToPeer::getInstance().connectConnOriented (jniHandle, nSap);
-
-    if (stat)
-        retVal = JNI_TRUE;
+    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o);
+    bool stat = PeerToPeer::getInstance().connectConnOriented (jniHandle, nSap);
 
     ALOGD ("%s: exit", __FUNCTION__);
-    return retVal;
+    return stat ? JNI_TRUE : JNI_FALSE;
 }
 
 
@@ -68,22 +63,17 @@
 static jboolean nativeLlcpSocket_doConnectBy (JNIEnv* e, jobject o, jstring sn)
 {
     ALOGD ("%s: enter", __FUNCTION__);
-    bool stat = false;
-    jboolean retVal = JNI_FALSE;
 
-    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle (e,o);
+    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o);
 
-    const char* serviceName = e->GetStringUTFChars (sn, JNI_FALSE); //convert jstring, which is unicode, into char*
-
-    stat = PeerToPeer::getInstance().connectConnOriented (jniHandle, serviceName);
-
-    e->ReleaseStringUTFChars (sn, serviceName); //free the string
-
-    if (stat)
-        retVal = JNI_TRUE;
+    ScopedUtfChars serviceName(e, sn);
+    if (serviceName.c_str() == NULL) {
+        return JNI_FALSE;
+    }
+    bool stat = PeerToPeer::getInstance().connectConnOriented(jniHandle, serviceName.c_str());
 
     ALOGD ("%s: exit", __FUNCTION__);
-    return retVal;
+    return stat ? JNI_TRUE : JNI_FALSE;
 }
 
 
@@ -101,16 +91,12 @@
 static jboolean nativeLlcpSocket_doClose(JNIEnv *e, jobject o)
 {
     ALOGD ("%s: enter", __FUNCTION__);
-    bool stat = false;
-    jboolean retVal = JNI_FALSE;
 
-    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle (e,o);
+    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o);
+    bool stat = PeerToPeer::getInstance().disconnectConnOriented (jniHandle);
 
-    stat = PeerToPeer::getInstance().disconnectConnOriented (jniHandle);
-
-    retVal = JNI_TRUE;
     ALOGD ("%s: exit", __FUNCTION__);
-    return retVal;
+    return JNI_TRUE; // TODO: stat?
 }
 
 
@@ -129,15 +115,12 @@
 static jboolean nativeLlcpSocket_doSend (JNIEnv* e, jobject o, jbyteArray data)
 {
     ALOGD_IF ((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "%s: enter", __FUNCTION__);
-    uint8_t* dataBuffer = (uint8_t*) e->GetByteArrayElements (data, NULL);
-    uint32_t dataBufferLen = (uint32_t) e->GetArrayLength (data);
-    bool stat = false;
 
-    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle (e,o);
+    ScopedByteArrayRO bytes(e, data);
 
-    stat = PeerToPeer::getInstance().send (jniHandle, dataBuffer, dataBufferLen);
-
-    e->ReleaseByteArrayElements (data, (jbyte*) dataBuffer, JNI_ABORT);
+    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o);
+    UINT8* raw_ptr = const_cast<UINT8*>(reinterpret_cast<const UINT8*>(&bytes[0])); // TODO: API bug: send should take const*!
+    bool stat = PeerToPeer::getInstance().send(jniHandle, raw_ptr, bytes.size());
 
     ALOGD_IF ((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "%s: exit", __FUNCTION__);
     return stat ? JNI_TRUE : JNI_FALSE;
@@ -159,24 +142,20 @@
 static jint nativeLlcpSocket_doReceive(JNIEnv *e, jobject o, jbyteArray origBuffer)
 {
     ALOGD_IF ((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "%s: enter", __FUNCTION__);
-    uint8_t* dataBuffer = (uint8_t*) e->GetByteArrayElements (origBuffer, NULL);
-    uint32_t dataBufferLen = (uint32_t) e->GetArrayLength (origBuffer);
+
+    ScopedByteArrayRW bytes(e, origBuffer);
+
+    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o);
     uint16_t actualLen = 0;
-    bool stat = false;
+    bool stat = PeerToPeer::getInstance().receive(jniHandle, reinterpret_cast<UINT8*>(&bytes[0]), bytes.size(), actualLen);
+
     jint retval = 0;
-
-    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle (e,o);
-
-    stat = PeerToPeer::getInstance().receive (jniHandle, dataBuffer, dataBufferLen, actualLen);
-
-    if (stat && (actualLen>0))
-    {
+    if (stat && (actualLen>0)) {
         retval = actualLen;
-    }
-    else
+    } else {
         retval = -1;
+    }
 
-    e->ReleaseByteArrayElements (origBuffer, (jbyte*) dataBuffer, 0);
     ALOGD_IF ((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "%s: exit; actual len=%d", __FUNCTION__, retval);
     return retval;
 }
@@ -196,12 +175,9 @@
 static jint nativeLlcpSocket_doGetRemoteSocketMIU (JNIEnv* e, jobject o)
 {
     ALOGD ("%s: enter", __FUNCTION__);
-    bool stat = false;
 
-    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle (e,o);
-    jint miu = 0;
-
-    miu = PeerToPeer::getInstance().getRemoteMaxInfoUnit (jniHandle);
+    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o);
+    jint miu = PeerToPeer::getInstance().getRemoteMaxInfoUnit(jniHandle);
 
     ALOGD ("%s: exit", __FUNCTION__);
     return miu;
@@ -222,12 +198,9 @@
 static jint nativeLlcpSocket_doGetRemoteSocketRW (JNIEnv* e, jobject o)
 {
     ALOGD ("%s: enter", __FUNCTION__);
-    bool stat = false;
-    jint rw = 0;
 
-    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle (e,o);
-
-    rw = PeerToPeer::getInstance().getRemoteRecvWindow (jniHandle);
+    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o);
+    jint rw = PeerToPeer::getInstance().getRemoteRecvWindow (jniHandle);
 
     ALOGD ("%s: exit", __FUNCTION__);
     return rw;
@@ -268,4 +241,3 @@
 
 
 } //namespace android
-
diff --git a/nci/jni/NativeNfcManager.cpp b/nci/jni/NativeNfcManager.cpp
index f15c92f..5bfe71a 100755
--- a/nci/jni/NativeNfcManager.cpp
+++ b/nci/jni/NativeNfcManager.cpp
@@ -27,6 +27,8 @@
 #include "PowerSwitch.h"
 #include "JavaClassConstants.h"
 #include "Pn544Interop.h"
+#include <ScopedLocalRef.h>
+#include <ScopedUtfChars.h>
 
 extern "C"
 {
@@ -115,13 +117,9 @@
 static bool                 sRfEnabled = false; // whether RF discovery is enabled
 static bool                 sSeRfActive = false;  // whether RF with SE is likely active
 static bool                 sP2pActive = false; // whether p2p was last active
-static int                  sConnlessSap = 0;
-static int                  sConnlessLinkMiu = 0;
 static bool                 sAbortConnlessWait = false;
 static bool                 sIsSecElemSelected = false;  //has NFC service selected a sec elem
 static UINT8 *              sOriginalLptdCfg = NULL;
-static UINT8                sNewLptdCfg[LPTD_PARAM_LEN];
-static UINT32               sConfigUpdated = 0;
 #define CONFIG_UPDATE_LPTD          (1 << 0)
 #define CONFIG_UPDATE_TECH_MASK     (1 << 1)
 #define DEFAULT_TECH_MASK           (NFA_TECHNOLOGY_MASK_A \
@@ -507,14 +505,9 @@
 *******************************************************************************/
 static jboolean nfcManager_initNativeStruc (JNIEnv* e, jobject o)
 {
-    nfc_jni_native_data* nat = NULL;
-    jclass cls = NULL;
-    jobject obj = NULL;
-    jfieldID f = 0;
-
     ALOGD ("%s: enter", __FUNCTION__);
 
-    nat = (nfc_jni_native_data*)malloc(sizeof(struct nfc_jni_native_data));
+    nfc_jni_native_data* nat = (nfc_jni_native_data*)malloc(sizeof(struct nfc_jni_native_data));
     if (nat == NULL)
     {
         ALOGE ("%s: fail allocate native data", __FUNCTION__);
@@ -522,50 +515,50 @@
     }
 
     memset (nat, 0, sizeof(*nat));
-    e->GetJavaVM (&(nat->vm));
-    nat->env_version = e->GetVersion ();
-    nat->manager = e->NewGlobalRef (o);
+    e->GetJavaVM(&(nat->vm));
+    nat->env_version = e->GetVersion();
+    nat->manager = e->NewGlobalRef(o);
 
-    cls = e->GetObjectClass (o);
-    f = e->GetFieldID (cls, "mNative", "I");
-    e->SetIntField (o, f, (jint)nat);
+    ScopedLocalRef<jclass> cls(e, e->GetObjectClass(o));
+    jfieldID f = e->GetFieldID(cls.get(), "mNative", "I");
+    e->SetIntField(o, f, (jint)nat);
 
     /* Initialize native cached references */
-    gCachedNfcManagerNotifyNdefMessageListeners = e->GetMethodID (cls,
+    gCachedNfcManagerNotifyNdefMessageListeners = e->GetMethodID(cls.get(),
             "notifyNdefMessageListeners", "(Lcom/android/nfc/dhimpl/NativeNfcTag;)V");
-    gCachedNfcManagerNotifyTransactionListeners = e->GetMethodID (cls,
+    gCachedNfcManagerNotifyTransactionListeners = e->GetMethodID(cls.get(),
             "notifyTransactionListeners", "([B)V");
-    gCachedNfcManagerNotifyLlcpLinkActivation = e->GetMethodID (cls,
+    gCachedNfcManagerNotifyLlcpLinkActivation = e->GetMethodID(cls.get(),
             "notifyLlcpLinkActivation", "(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");
-    gCachedNfcManagerNotifyLlcpLinkDeactivated = e->GetMethodID (cls,
+    gCachedNfcManagerNotifyLlcpLinkDeactivated = e->GetMethodID(cls.get(),
             "notifyLlcpLinkDeactivated", "(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");
-    sCachedNfcManagerNotifyTargetDeselected = e->GetMethodID (cls,
+    sCachedNfcManagerNotifyTargetDeselected = e->GetMethodID(cls.get(),
             "notifyTargetDeselected","()V");
-    gCachedNfcManagerNotifySeFieldActivated = e->GetMethodID (cls,
+    gCachedNfcManagerNotifySeFieldActivated = e->GetMethodID(cls.get(),
             "notifySeFieldActivated", "()V");
-    gCachedNfcManagerNotifySeFieldDeactivated = e->GetMethodID (cls,
+    gCachedNfcManagerNotifySeFieldDeactivated = e->GetMethodID(cls.get(),
             "notifySeFieldDeactivated", "()V");
-    gCachedNfcManagerNotifySeListenActivated = e->GetMethodID (cls,
+    gCachedNfcManagerNotifySeListenActivated = e->GetMethodID(cls.get(),
             "notifySeListenActivated", "()V");
-    gCachedNfcManagerNotifySeListenDeactivated = e->GetMethodID (cls,
+    gCachedNfcManagerNotifySeListenDeactivated = e->GetMethodID(cls.get(),
             "notifySeListenDeactivated", "()V");
 
-    sCachedNfcManagerNotifySeApduReceived = e->GetMethodID(cls,
+    sCachedNfcManagerNotifySeApduReceived = e->GetMethodID(cls.get(),
             "notifySeApduReceived", "([B)V");
 
-    sCachedNfcManagerNotifySeMifareAccess = e->GetMethodID(cls,
+    sCachedNfcManagerNotifySeMifareAccess = e->GetMethodID(cls.get(),
             "notifySeMifareAccess", "([B)V");
 
-    sCachedNfcManagerNotifySeEmvCardRemoval =  e->GetMethodID(cls,
+    sCachedNfcManagerNotifySeEmvCardRemoval =  e->GetMethodID(cls.get(),
             "notifySeEmvCardRemoval", "()V");
 
-    if (nfc_jni_cache_object(e,gNativeNfcTagClassName, &(nat->cached_NfcTag)) == -1)
+    if (nfc_jni_cache_object(e, gNativeNfcTagClassName, &(nat->cached_NfcTag)) == -1)
     {
         ALOGE ("%s: fail cache NativeNfcTag", __FUNCTION__);
         return JNI_FALSE;
     }
 
-    if (nfc_jni_cache_object(e,gNativeP2pDeviceClassName, &(nat->cached_P2pDevice)) == -1)
+    if (nfc_jni_cache_object(e, gNativeP2pDeviceClassName, &(nat->cached_P2pDevice)) == -1)
     {
         ALOGE ("%s: fail cache NativeP2pDevice", __FUNCTION__);
         return JNI_FALSE;
@@ -884,7 +877,7 @@
 ** Returns:         None
 **
 *******************************************************************************/
-void nfcManager_disableDiscovery (JNIEnv* e, jobject o)
+void nfcManager_disableDiscovery (JNIEnv*, jobject)
 {
     tNFA_STATUS status = NFA_STATUS_OK;
     ALOGD ("%s: enter;", __FUNCTION__);
@@ -931,35 +924,26 @@
 ** Returns          -1 on failure, 0 on success
 **
 *******************************************************************************/
-int nfc_jni_cache_object_local (JNIEnv *e, const char *className, jobject *cachedObj)
+static int nfc_jni_cache_object_local (JNIEnv *e, const char *className, jobject *cachedObj)
 {
-    jclass cls = NULL;
-    jobject obj = NULL;
-    jmethodID ctor = 0;
-
-    cls = e->FindClass (className);
-    if(cls == NULL)
-    {
+    ScopedLocalRef<jclass> cls(e, e->FindClass(className));
+    if(cls.get() == NULL) {
         ALOGE ("%s: find class error", __FUNCTION__);
         return -1;
     }
 
-    ctor = e->GetMethodID (cls, "<init>", "()V");
-    obj = e->NewObject (cls, ctor);
-    if (obj == NULL)
-    {
+    jmethodID ctor = e->GetMethodID(cls.get(), "<init>", "()V");
+    jobject obj = e->NewObject(cls.get(), ctor);
+    if (obj == NULL) {
        ALOGE ("%s: create object error", __FUNCTION__);
        return -1;
     }
 
-    *cachedObj = e->NewLocalRef (obj);
-    if (*cachedObj == NULL)
-    {
-        e->DeleteLocalRef (obj);
+    *cachedObj = obj;
+    if (*cachedObj == NULL) {
         ALOGE ("%s: global ref error", __FUNCTION__);
         return -1;
     }
-    e->DeleteLocalRef (obj);
     return 0;
 }
 
@@ -980,20 +964,16 @@
 ** Returns:         NativeLlcpServiceSocket Java object.
 **
 *******************************************************************************/
-static jobject nfcManager_doCreateLlcpServiceSocket (JNIEnv* e, jobject o, jint nSap, jstring sn, jint miu, jint rw, jint linearBufferLength)
+static jobject nfcManager_doCreateLlcpServiceSocket (JNIEnv* e, jobject, jint nSap, jstring sn, jint miu, jint rw, jint linearBufferLength)
 {
-    bool        stat = false;
-    jobject     serviceSocket = NULL;
-    jclass      clsNativeLlcpServiceSocket = NULL;
-    jfieldID    f = 0;
     PeerToPeer::tJNI_HANDLE jniHandle = PeerToPeer::getInstance().getNewJniHandle ();
-    const char* serviceName = e->GetStringUTFChars (sn, JNI_FALSE); //convert jstring, which is unicode, into char*
-    std::string serviceName2 (serviceName);
 
-    e->ReleaseStringUTFChars (sn, serviceName); //free the string
-    ALOGD ("%s: enter: sap=%i; name=%s; miu=%i; rw=%i; buffLen=%i", __FUNCTION__, nSap, serviceName2.c_str(), miu, rw, linearBufferLength);
+    ScopedUtfChars serviceName(e, sn);
+
+    ALOGD ("%s: enter: sap=%i; name=%s; miu=%i; rw=%i; buffLen=%i", __FUNCTION__, nSap, serviceName.c_str(), miu, rw, linearBufferLength);
 
     /* Create new NativeLlcpServiceSocket object */
+    jobject serviceSocket = NULL;
     if (nfc_jni_cache_object(e, gNativeLlcpServiceSocketClassName, &(serviceSocket)) == -1)
     {
         ALOGE ("%s: Llcp socket object creation error", __FUNCTION__);
@@ -1001,7 +981,7 @@
     }
 
     /* Get NativeLlcpServiceSocket class object */
-    clsNativeLlcpServiceSocket = e->GetObjectClass (serviceSocket);
+    ScopedLocalRef<jclass> clsNativeLlcpServiceSocket(e, e->GetObjectClass(serviceSocket));
     if (e->ExceptionCheck())
     {
         e->ExceptionClear();
@@ -1009,30 +989,32 @@
         return NULL;
     }
 
-    if (!PeerToPeer::getInstance().registerServer (jniHandle, serviceName2.c_str()))
+    if (!PeerToPeer::getInstance().registerServer (jniHandle, serviceName.c_str()))
     {
         ALOGE("%s: RegisterServer error", __FUNCTION__);
         return NULL;
     }
 
+    jfieldID f;
+
     /* Set socket handle to be the same as the NfaHandle*/
-    f = e->GetFieldID (clsNativeLlcpServiceSocket, "mHandle", "I");
-    e->SetIntField (serviceSocket, f, (jint) jniHandle);
+    f = e->GetFieldID(clsNativeLlcpServiceSocket.get(), "mHandle", "I");
+    e->SetIntField(serviceSocket, f, (jint) jniHandle);
     ALOGD ("%s: socket Handle = 0x%X", __FUNCTION__, jniHandle);
 
     /* Set socket linear buffer length */
-    f = e->GetFieldID (clsNativeLlcpServiceSocket, "mLocalLinearBufferLength", "I");
-    e->SetIntField (serviceSocket, f,(jint)linearBufferLength);
+    f = e->GetFieldID(clsNativeLlcpServiceSocket.get(), "mLocalLinearBufferLength", "I");
+    e->SetIntField(serviceSocket, f,(jint)linearBufferLength);
     ALOGD ("%s: buffer length = %d", __FUNCTION__, linearBufferLength);
 
     /* Set socket MIU */
-    f = e->GetFieldID (clsNativeLlcpServiceSocket, "mLocalMiu", "I");
-    e->SetIntField (serviceSocket, f,(jint)miu);
+    f = e->GetFieldID(clsNativeLlcpServiceSocket.get(), "mLocalMiu", "I");
+    e->SetIntField(serviceSocket, f,(jint)miu);
     ALOGD ("%s: MIU = %d", __FUNCTION__, miu);
 
     /* Set socket RW */
-    f = e->GetFieldID (clsNativeLlcpServiceSocket, "mLocalRw", "I");
-    e->SetIntField (serviceSocket, f,(jint)rw);
+    f = e->GetFieldID(clsNativeLlcpServiceSocket.get(), "mLocalRw", "I");
+    e->SetIntField(serviceSocket, f,(jint)rw);
     ALOGD ("%s:  RW = %d", __FUNCTION__, rw);
 
     sLastError = 0;
@@ -1052,7 +1034,7 @@
 ** Returns:         Last error code.
 **
 *******************************************************************************/
-static jint nfcManager_doGetLastError(JNIEnv* e, jobject o)
+static jint nfcManager_doGetLastError(JNIEnv*, jobject)
 {
     ALOGD ("%s: last error=%i", __FUNCTION__, sLastError);
     return sLastError;
@@ -1070,7 +1052,7 @@
 ** Returns:         True if ok.
 **
 *******************************************************************************/
-static jboolean nfcManager_doDeinitialize (JNIEnv* e, jobject o)
+static jboolean nfcManager_doDeinitialize (JNIEnv*, jobject)
 {
     ALOGD ("%s: enter", __FUNCTION__);
 
@@ -1131,50 +1113,48 @@
 ** Returns:         NativeLlcpSocket Java object.
 **
 *******************************************************************************/
-static jobject nfcManager_doCreateLlcpSocket (JNIEnv* e, jobject o, jint nSap, jint miu, jint rw, jint linearBufferLength)
+static jobject nfcManager_doCreateLlcpSocket (JNIEnv* e, jobject, jint nSap, jint miu, jint rw, jint linearBufferLength)
 {
     ALOGD ("%s: enter; sap=%d; miu=%d; rw=%d; buffer len=%d", __FUNCTION__, nSap, miu, rw, linearBufferLength);
-    jobject clientSocket = NULL;
-    jclass clsNativeLlcpSocket;
-    jfieldID f;
-    PeerToPeer::tJNI_HANDLE jniHandle = PeerToPeer::getInstance().getNewJniHandle ();
-    bool stat = false;
 
-    stat = PeerToPeer::getInstance().createClient (jniHandle, miu, rw);
+    PeerToPeer::tJNI_HANDLE jniHandle = PeerToPeer::getInstance().getNewJniHandle ();
+    bool stat = PeerToPeer::getInstance().createClient (jniHandle, miu, rw);
 
     /* Create new NativeLlcpSocket object */
+    jobject clientSocket = NULL;
     if (nfc_jni_cache_object_local(e, gNativeLlcpSocketClassName, &(clientSocket)) == -1)
     {
         ALOGE ("%s: fail Llcp socket creation", __FUNCTION__);
-        goto TheEnd;
+        return clientSocket;
     }
 
     /* Get NativeConnectionless class object */
-    clsNativeLlcpSocket = e->GetObjectClass (clientSocket);
+    ScopedLocalRef<jclass> clsNativeLlcpSocket(e, e->GetObjectClass(clientSocket));
     if (e->ExceptionCheck())
     {
         e->ExceptionClear();
         ALOGE ("%s: fail get class object", __FUNCTION__);
-        goto TheEnd;
+        return clientSocket;
     }
 
+    jfieldID f;
+
     /* Set socket SAP */
-    f = e->GetFieldID (clsNativeLlcpSocket, "mSap", "I");
+    f = e->GetFieldID (clsNativeLlcpSocket.get(), "mSap", "I");
     e->SetIntField (clientSocket, f, (jint) nSap);
 
     /* Set socket handle */
-    f = e->GetFieldID (clsNativeLlcpSocket, "mHandle", "I");
+    f = e->GetFieldID (clsNativeLlcpSocket.get(), "mHandle", "I");
     e->SetIntField (clientSocket, f, (jint) jniHandle);
 
     /* Set socket MIU */
-    f = e->GetFieldID (clsNativeLlcpSocket, "mLocalMiu", "I");
+    f = e->GetFieldID (clsNativeLlcpSocket.get(), "mLocalMiu", "I");
     e->SetIntField (clientSocket, f, (jint) miu);
 
     /* Set socket RW */
-    f = e->GetFieldID (clsNativeLlcpSocket, "mLocalRw", "I");
+    f = e->GetFieldID (clsNativeLlcpSocket.get(), "mLocalRw", "I");
     e->SetIntField (clientSocket, f, (jint) rw);
 
-TheEnd:
     ALOGD ("%s: exit", __FUNCTION__);
     return clientSocket;
 }
@@ -1193,7 +1173,7 @@
 ** Returns:         NativeLlcpConnectionlessSocket Java object.
 **
 *******************************************************************************/
-static jobject nfcManager_doCreateLlcpConnectionlessSocket (JNIEnv *e, jobject o, jint nSap, jstring sn)
+static jobject nfcManager_doCreateLlcpConnectionlessSocket (JNIEnv *, jobject, jint nSap, jstring /*sn*/)
 {
     ALOGD ("%s: nSap=0x%X", __FUNCTION__, nSap);
     return NULL;
@@ -1211,7 +1191,7 @@
 ** Returns:         List of secure element handles.
 **
 *******************************************************************************/
-static jintArray nfcManager_doGetSecureElementList(JNIEnv *e, jobject o)
+static jintArray nfcManager_doGetSecureElementList(JNIEnv* e, jobject)
 {
     ALOGD ("%s", __FUNCTION__);
     return SecureElement::getInstance().getListOfEeHandles (e);
@@ -1229,7 +1209,7 @@
 ** Returns:         None
 **
 *******************************************************************************/
-static void nfcManager_doSelectSecureElement(JNIEnv *e, jobject o)
+static void nfcManager_doSelectSecureElement(JNIEnv*, jobject)
 {
     ALOGD ("%s: enter", __FUNCTION__);
     bool stat = true;
@@ -1272,7 +1252,7 @@
 ** Returns:         None
 **
 *******************************************************************************/
-static void nfcManager_doDeselectSecureElement(JNIEnv *e, jobject o)
+static void nfcManager_doDeselectSecureElement(JNIEnv*, jobject)
 {
     ALOGD ("%s: enter", __FUNCTION__);
     bool stat = false;
@@ -1352,7 +1332,7 @@
 ** Returns:         True
 **
 *******************************************************************************/
-static jboolean nfcManager_doCheckLlcp(JNIEnv *e, jobject o)
+static jboolean nfcManager_doCheckLlcp(JNIEnv*, jobject)
 {
     ALOGD("%s", __FUNCTION__);
     return JNI_TRUE;
@@ -1368,7 +1348,7 @@
 ** Returns:         True
 **
 *******************************************************************************/
-static jboolean nfcManager_doActivateLlcp(JNIEnv *e, jobject o)
+static jboolean nfcManager_doActivateLlcp(JNIEnv*, jobject)
 {
     ALOGD("%s", __FUNCTION__);
     return JNI_TRUE;
@@ -1384,7 +1364,7 @@
 ** Returns:         None
 **
 *******************************************************************************/
-static void nfcManager_doAbort(JNIEnv *e, jobject o)
+static void nfcManager_doAbort(JNIEnv*, jobject)
 {
     ALOGE("%s: abort()", __FUNCTION__);
     abort();
@@ -1400,7 +1380,7 @@
 ** Returns:         True
 **
 *******************************************************************************/
-static jboolean nfcManager_doDownload(JNIEnv *e, jobject o)
+static jboolean nfcManager_doDownload(JNIEnv*, jobject)
 {
     ALOGD("%s", __FUNCTION__);
     return JNI_TRUE;
@@ -1416,7 +1396,7 @@
 ** Returns:         None
 **
 *******************************************************************************/
-static void nfcManager_doResetTimeouts(JNIEnv *e, jobject o)
+static void nfcManager_doResetTimeouts(JNIEnv*, jobject)
 {
     ALOGD ("%s: %d millisec", __FUNCTION__, DEFAULT_GENERAL_TRANS_TIMEOUT);
     gGeneralTransceiveTimeout = DEFAULT_GENERAL_TRANS_TIMEOUT;
@@ -1435,7 +1415,7 @@
 ** Returns:         True if ok.
 **
 *******************************************************************************/
-static bool nfcManager_doSetTimeout(JNIEnv *e, jobject o, jint tech, jint timeout)
+static bool nfcManager_doSetTimeout(JNIEnv*, jobject, jint /*tech*/, jint timeout)
 {
     if (timeout <= 0)
     {
@@ -1461,7 +1441,7 @@
 ** Returns:         Timeout value.
 **
 *******************************************************************************/
-static jint nfcManager_doGetTimeout(JNIEnv *e, jobject o, jint tech)
+static jint nfcManager_doGetTimeout(JNIEnv*, jobject, jint /*tech*/)
 {
     ALOGD ("%s: timeout=%d", __FUNCTION__, gGeneralTransceiveTimeout);
     return gGeneralTransceiveTimeout;
@@ -1479,7 +1459,7 @@
 ** Returns:         Text dump.
 **
 *******************************************************************************/
-static jstring nfcManager_doDump(JNIEnv *e, jobject o)
+static jstring nfcManager_doDump(JNIEnv* e, jobject)
 {
     char buffer[100];
     snprintf(buffer, sizeof(buffer), "libnfc llc error_count=%u", /*libnfc_llc_error_count*/ 0);
@@ -1531,7 +1511,7 @@
 ** Returns:         None.
 **
 *******************************************************************************/
-static void nfcManager_doSetP2pTargetModes (JNIEnv *e, jobject o, jint modes)
+static void nfcManager_doSetP2pTargetModes (JNIEnv*, jobject, jint modes)
 {
     ALOGD ("%s: modes=0x%X", __FUNCTION__, modes);
     // Map in the right modes
diff --git a/nci/jni/NativeNfcTag.cpp b/nci/jni/NativeNfcTag.cpp
index 0ba7b21..5e0a917 100755
--- a/nci/jni/NativeNfcTag.cpp
+++ b/nci/jni/NativeNfcTag.cpp
@@ -26,6 +26,8 @@
 #include "IntervalTimer.h"
 #include "JavaClassConstants.h"
 #include "Pn544Interop.h"
+#include <ScopedLocalRef.h>
+#include <ScopedPrimitiveArray.h>
 
 extern "C"
 {
@@ -244,7 +246,7 @@
 ** Returns:         NDEF message.
 **
 *******************************************************************************/
-static jbyteArray nativeNfcTag_doRead (JNIEnv *e, jobject o)
+static jbyteArray nativeNfcTag_doRead (JNIEnv* e, jobject)
 {
     ALOGD ("%s: enter", __FUNCTION__);
     tNFA_STATUS status = NFA_STATUS_FAILED;
@@ -277,7 +279,6 @@
     else
     {
         ALOGD ("%s: create emtpy buffer", __FUNCTION__);
-        static uint8_t* empty = (uint8_t*) "";
         sReadDataLen = 0;
         sReadData = (uint8_t*) malloc (1);
         buf = e->NewByteArray (sReadDataLen);
@@ -348,20 +349,18 @@
 ** Returns:         True if ok.
 **
 *******************************************************************************/
-static jboolean nativeNfcTag_doWrite (JNIEnv *e, jobject o, jbyteArray buf)
+static jboolean nativeNfcTag_doWrite (JNIEnv* e, jobject, jbyteArray buf)
 {
     jboolean result = JNI_FALSE;
     tNFA_STATUS status = 0;
-    UINT32 len = 0;
-    UINT8* p_data = NULL;
     const int maxBufferSize = 1024;
     UINT8 buffer[maxBufferSize] = { 0 };
     UINT32 curDataSize = 0;
 
-    len = (UINT32) e->GetArrayLength (buf);
-    p_data = (UINT8*) e->GetByteArrayElements (buf, NULL);
+    ScopedByteArrayRO bytes(e, buf);
+    UINT8* p_data = const_cast<UINT8*>(reinterpret_cast<const UINT8*>(&bytes[0])); // TODO: const-ness API bug in NFA_RwWriteNDef!
 
-    ALOGD ("%s: enter; len = %lu", __FUNCTION__, len);
+    ALOGD ("%s: enter; len = %zu", __FUNCTION__, bytes.size());
 
     /* Create the write semaphore */
     if (sem_init (&sWriteSem, 0, 0) == -1)
@@ -387,9 +386,9 @@
                 goto TheEnd;
         }
         ALOGD ("%s: try write", __FUNCTION__);
-        status = NFA_RwWriteNDef (p_data, len);
+        status = NFA_RwWriteNDef (p_data, bytes.size());
     }
-    else if (len == 0)
+    else if (bytes.size() == 0)
     {
         //if (NXP TagWriter wants to erase tag) then create and write an empty ndef message
         NDEF_MsgInit (buffer, maxBufferSize, &curDataSize);
@@ -400,7 +399,7 @@
     else
     {
         ALOGD ("%s: NFA_RwWriteNDef", __FUNCTION__);
-        status = NFA_RwWriteNDef (p_data, len);
+        status = NFA_RwWriteNDef (p_data, bytes.size());
     }
 
     if (status != NFA_STATUS_OK)
@@ -483,7 +482,7 @@
 ** Returns:         Must return NXP status code, which NFC service expects.
 **
 *******************************************************************************/
-static jint nativeNfcTag_doConnect (JNIEnv *e, jobject o, jint targetHandle)
+static jint nativeNfcTag_doConnect (JNIEnv*, jobject, jint targetHandle)
 {
     ALOGD ("%s: targetHandle = %d", __FUNCTION__, targetHandle);
     int i = targetHandle;
@@ -671,7 +670,7 @@
 ** Returns:         Status code.
 **
 *******************************************************************************/
-static jint nativeNfcTag_doReconnect (JNIEnv *e, jobject o)
+static jint nativeNfcTag_doReconnect (JNIEnv*, jobject)
 {
     ALOGD ("%s: enter", __FUNCTION__);
     int retCode = NFCSTATUS_SUCCESS;
@@ -726,7 +725,7 @@
 ** Returns:         True if ok.
 **
 *******************************************************************************/
-static jboolean nativeNfcTag_doDisconnect (JNIEnv *e, jobject o)
+static jboolean nativeNfcTag_doDisconnect (JNIEnv*, jobject)
 {
     ALOGD ("%s: enter", __FUNCTION__);
     struct nfc_jni_native_data *nat = getNative (0, 0);
@@ -800,15 +799,13 @@
 ** Returns:         Response from tag.
 **
 *******************************************************************************/
-static jbyteArray nativeNfcTag_doTransceive (JNIEnv *e, jobject o, jbyteArray data, jboolean raw, jintArray statusTargetLost)
+static jbyteArray nativeNfcTag_doTransceive (JNIEnv* e, jobject, jbyteArray data, jboolean raw, jintArray statusTargetLost)
 {
     ALOGD ("%s: enter; raw=%u; timeout = %d", __FUNCTION__, raw, gGeneralTransceiveTimeout);
     bool fNeedToSwitchBack = false;
     nfc_jni_native_data *nat = getNative (0, 0);
     bool waitOk = false;
     bool isNack = false;
-    uint8_t *buf = NULL;
-    uint32_t bufLen = 0;
     jint *targetLost = NULL;
 
     if (NfcTag::getInstance ().getActivationState () != NfcTag::Active)
@@ -827,8 +824,9 @@
     NfcTag& natTag = NfcTag::getInstance ();
 
     // get input buffer and length from java call
-    buf = (uint8_t *) e->GetByteArrayElements (data, NULL);
-    bufLen = (uint32_t) e->GetArrayLength (data);
+    ScopedByteArrayRO bytes(e, data);
+    uint8_t* buf = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&bytes[0])); // TODO: API bug; NFA_SendRawFrame should take const*!
+    size_t bufLen = bytes.size();
 
     if (statusTargetLost)
     {
@@ -838,7 +836,7 @@
     }
 
     sSwitchBackTimer.kill ();
-    jbyteArray result = NULL;
+    ScopedLocalRef<jbyteArray> result(e, NULL);
     do
     {
         if (sNeedToSwitchRf)
@@ -892,10 +890,9 @@
         {
             if (!isNack) {
                 // marshall data to java for return
-                result = e->NewByteArray (sTransceiveDataLen);
-                if (result != NULL)
-                {
-                    e->SetByteArrayRegion (result, 0, sTransceiveDataLen, (jbyte *) sTransceiveData);
+                result.reset(e->NewByteArray(sTransceiveDataLen));
+                if (result.get() != NULL) {
+                    e->SetByteArrayRegion(result.get(), 0, sTransceiveDataLen, (jbyte *) sTransceiveData);
                 }
                 else
                     ALOGE ("%s: Failed to allocate java byte array", __FUNCTION__);
@@ -908,7 +905,6 @@
     } while (0);
 
     sWaitingForTransceive = false;
-    e->ReleaseByteArrayElements (data, (jbyte *) buf, JNI_ABORT);
     if (targetLost)
         e->ReleaseIntArrayElements (statusTargetLost, targetLost, 0);
 
@@ -919,7 +915,7 @@
     }
 
     ALOGD ("%s: exit", __FUNCTION__);
-    return result;
+    return result.release();
 }
 
 
@@ -936,7 +932,7 @@
 ** Returns:         Type of tag represented by NFC Service.
 **
 *******************************************************************************/
-static jint nativeNfcTag_doGetNdefType (JNIEnv *e, jobject o, jint libnfcType, jint javaType)
+static jint nativeNfcTag_doGetNdefType (JNIEnv*, jobject, jint libnfcType, jint javaType)
 {
     ALOGD ("%s: enter; libnfc type=%d; java type=%d", __FUNCTION__, libnfcType, javaType);
     jint ndefType = NDEF_UNKNOWN_TYPE;
@@ -1064,7 +1060,7 @@
 ** Returns:         Status code; 0 is success.
 **
 *******************************************************************************/
-static jint nativeNfcTag_doCheckNdef (JNIEnv *e, jobject o, jintArray ndefInfo)
+static jint nativeNfcTag_doCheckNdef (JNIEnv* e, jobject, jintArray ndefInfo)
 {
     tNFA_STATUS status = NFA_STATUS_FAILED;
     jint* ndef = NULL;
@@ -1202,7 +1198,7 @@
 ** Returns:         True if tag is in RF field.
 **
 *******************************************************************************/
-static jboolean nativeNfcTag_doPresenceCheck (JNIEnv *e, jobject o)
+static jboolean nativeNfcTag_doPresenceCheck (JNIEnv*, jobject)
 {
     ALOGD ("%s", __FUNCTION__);
     tNFA_STATUS status = NFA_STATUS_OK;
@@ -1265,9 +1261,9 @@
 ** Returns:         True if formattable.
 **
 *******************************************************************************/
-static jboolean nativeNfcTag_doIsNdefFormatable (JNIEnv *e,
-        jobject o, jint libNfcType, jbyteArray uidBytes, jbyteArray pollBytes,
-        jbyteArray actBytes)
+static jboolean nativeNfcTag_doIsNdefFormatable (JNIEnv*,
+        jobject, jint /*libNfcType*/, jbyteArray, jbyteArray,
+        jbyteArray)
 {
     jboolean isFormattable = JNI_FALSE;
 
@@ -1321,7 +1317,7 @@
 ** Returns:         True if ok.
 **
 *******************************************************************************/
-static jboolean nativeNfcTag_doNdefFormat (JNIEnv *e, jobject o, jbyteArray key)
+static jboolean nativeNfcTag_doNdefFormat (JNIEnv*, jobject, jbyteArray)
 {
     ALOGD ("%s: enter", __FUNCTION__);
     tNFA_STATUS status = NFA_STATUS_OK;
@@ -1379,7 +1375,7 @@
 ** Returns:         True if ok.
 **
 *******************************************************************************/
-static jboolean nativeNfcTag_doMakeReadonly (JNIEnv *e, jobject o, jbyteArray key)
+static jboolean nativeNfcTag_doMakeReadonly (JNIEnv*, jobject, jbyteArray)
 {
     jboolean result = JNI_FALSE;
     tNFA_STATUS status;
diff --git a/nci/jni/NativeP2pDevice.cpp b/nci/jni/NativeP2pDevice.cpp
index 57f9dad..fffa46b 100644
--- a/nci/jni/NativeP2pDevice.cpp
+++ b/nci/jni/NativeP2pDevice.cpp
@@ -23,35 +23,35 @@
 {
 
 
-static jboolean nativeP2pDeviceDoConnect (JNIEnv* e, jobject o)
+static jboolean nativeP2pDeviceDoConnect (JNIEnv*, jobject)
 {
     ALOGD ("%s", __FUNCTION__);
     return JNI_TRUE;
 }
 
 
-static jboolean nativeP2pDeviceDoDisconnect (JNIEnv* e, jobject o)
+static jboolean nativeP2pDeviceDoDisconnect (JNIEnv*, jobject)
 {
     ALOGD ("%s", __FUNCTION__);
     return JNI_TRUE;
 }
 
 
-static jbyteArray nativeP2pDeviceDoTransceive (JNIEnv* e, jobject o, jbyteArray data)
+static jbyteArray nativeP2pDeviceDoTransceive (JNIEnv*, jobject, jbyteArray)
 {
     ALOGD ("%s", __FUNCTION__);
     return NULL;
 }
 
 
-static jbyteArray nativeP2pDeviceDoReceive (JNIEnv* e, jobject o)
+static jbyteArray nativeP2pDeviceDoReceive (JNIEnv*, jobject)
 {
     ALOGD ("%s", __FUNCTION__);
     return NULL;
 }
 
 
-static jboolean nativeP2pDeviceDoSend (JNIEnv* e, jobject o, jbyteArray buf)
+static jboolean nativeP2pDeviceDoSend (JNIEnv*, jobject, jbyteArray)
 {
     ALOGD ("%s", __FUNCTION__);
     return JNI_TRUE;
diff --git a/nci/jni/NativeSecureElement.cpp b/nci/jni/NativeSecureElement.cpp
index 1a2a73a..d1438bc 100755
--- a/nci/jni/NativeSecureElement.cpp
+++ b/nci/jni/NativeSecureElement.cpp
@@ -17,7 +17,7 @@
 #include "SecureElement.h"
 #include "JavaClassConstants.h"
 #include "PowerSwitch.h"
-
+#include <ScopedPrimitiveArray.h>
 
 namespace android
 {
@@ -39,7 +39,7 @@
 ** Returns:         Handle of secure element.  0 is failure.
 **
 *******************************************************************************/
-static jint nativeNfcSecureElement_doOpenSecureElementConnection (JNIEnv* e, jobject o)
+static jint nativeNfcSecureElement_doOpenSecureElementConnection (JNIEnv*, jobject)
 {
     ALOGD("%s: enter", __FUNCTION__);
     bool stat = true;
@@ -99,7 +99,7 @@
 ** Returns:         True if ok.
 **
 *******************************************************************************/
-static jboolean nativeNfcSecureElement_doDisconnectSecureElementConnection (JNIEnv* e, jobject o, jint handle)
+static jboolean nativeNfcSecureElement_doDisconnectSecureElementConnection (JNIEnv*, jobject, jint handle)
 {
     ALOGD("%s: enter; handle=0x%04x", __FUNCTION__, handle);
     bool stat = false;
@@ -133,29 +133,23 @@
 ** Returns:         Buffer of received data.
 **
 *******************************************************************************/
-static jbyteArray nativeNfcSecureElement_doTransceive (JNIEnv* e, jobject o, jint handle, jbyteArray data)
+static jbyteArray nativeNfcSecureElement_doTransceive (JNIEnv* e, jobject, jint handle, jbyteArray data)
 {
-    UINT8* buf = NULL;
-    INT32 buflen = 0;
     const INT32 recvBufferMaxSize = 1024;
     UINT8 recvBuffer [recvBufferMaxSize];
     INT32 recvBufferActualSize = 0;
-    jbyteArray result = NULL;
 
-    buf = (UINT8*) e->GetByteArrayElements (data, NULL);
-    buflen = e->GetArrayLength (data);
+    ScopedByteArrayRW bytes(e, data);
 
-    ALOGD("%s: enter; handle=0x%X; buf len=%ld", __FUNCTION__, handle, buflen);
-    SecureElement::getInstance().transceive (buf, buflen, recvBuffer, recvBufferMaxSize, recvBufferActualSize, gGeneralTransceiveTimeout);
+    ALOGD("%s: enter; handle=0x%X; buf len=%zu", __FUNCTION__, handle, bytes.size());
+    SecureElement::getInstance().transceive(reinterpret_cast<UINT8*>(&bytes[0]), bytes.size(), recvBuffer, recvBufferMaxSize, recvBufferActualSize, gGeneralTransceiveTimeout);
 
     //copy results back to java
-    result = e->NewByteArray (recvBufferActualSize);
-    if (result != NULL)
-    {
-        e->SetByteArrayRegion (result, 0, recvBufferActualSize, (jbyte *) recvBuffer);
+    jbyteArray result = e->NewByteArray(recvBufferActualSize);
+    if (result != NULL) {
+        e->SetByteArrayRegion(result, 0, recvBufferActualSize, (jbyte *) recvBuffer);
     }
 
-    e->ReleaseByteArrayElements (data, (jbyte *) buf, JNI_ABORT);
     ALOGD("%s: exit: recv len=%ld", __FUNCTION__, recvBufferActualSize);
     return result;
 }
@@ -173,7 +167,7 @@
 ** Returns:         Secure element's unique ID.
 **
 *******************************************************************************/
-static jbyteArray nativeNfcSecureElement_doGetUid (JNIEnv* e, jobject o, jint handle)
+static jbyteArray nativeNfcSecureElement_doGetUid (JNIEnv*, jobject, jint handle)
 {
     ALOGD("%s: enter; handle=0x%X", __FUNCTION__, handle);
     jbyteArray secureElementUid = NULL;
@@ -197,7 +191,7 @@
 ** Returns:         Array of technologies.
 **
 *******************************************************************************/
-static jintArray nativeNfcSecureElement_doGetTechList (JNIEnv* e, jobject o, jint handle)
+static jintArray nativeNfcSecureElement_doGetTechList (JNIEnv*, jobject, jint handle)
 {
     ALOGD("%s: enter; handle=0x%X", __FUNCTION__, handle);
     jintArray techList = NULL;
@@ -242,4 +236,3 @@
 
 
 } // namespace android
-
diff --git a/nci/jni/NfcJniUtil.cpp b/nci/jni/NfcJniUtil.cpp
index 9921cae..2bac97b 100755
--- a/nci/jni/NfcJniUtil.cpp
+++ b/nci/jni/NfcJniUtil.cpp
@@ -15,6 +15,7 @@
  */
 #include "NfcJniUtil.h"
 #include <errno.h>
+#include <ScopedLocalRef.h>
 
 
 /*******************************************************************************
@@ -28,11 +29,13 @@
 ** Returns:         JNI version.
 **
 *******************************************************************************/
-jint JNI_OnLoad (JavaVM *jvm, void *reserved)
+jint JNI_OnLoad (JavaVM* jvm, void*)
 {
     ALOGD ("%s: enter", __FUNCTION__);
     JNIEnv *e = NULL;
 
+    ALOGI("NFC Service: loading nci JNI");
+
     // Check JNI version
     if (jvm->GetEnv ((void **) &e, JNI_VERSION_1_6))
         return JNI_ERR;
@@ -71,33 +74,24 @@
 *******************************************************************************/
 int nfc_jni_cache_object (JNIEnv *e, const char *className, jobject *cachedObj)
 {
-    jclass cls = NULL;
-    jobject obj = NULL;
-    jmethodID ctor = 0;
-
-    cls = e->FindClass (className);
-    if(cls == NULL)
-    {
-        ALOGE ("%s: find class error", __FUNCTION__);
+    ScopedLocalRef<jclass> cls(e, e->FindClass(className));
+    if (cls.get() == NULL) {
+        ALOGE("%s: find class error", __FUNCTION__);
         return -1;
     }
 
-    ctor = e->GetMethodID (cls, "<init>", "()V");
-    obj = e->NewObject (cls, ctor);
-    if (obj == NULL)
-    {
-       ALOGE ("%s: create object error", __FUNCTION__);
+    jmethodID ctor = e->GetMethodID(cls.get(), "<init>", "()V");
+    ScopedLocalRef<jobject> obj(e, e->NewObject(cls.get(), ctor));
+    if (obj.get() == NULL) {
+       ALOGE("%s: create object error", __FUNCTION__);
        return -1;
     }
 
-    *cachedObj = e->NewGlobalRef (obj);
-    if (*cachedObj == NULL)
-    {
-        e->DeleteLocalRef (obj);
-        ALOGE ("%s: global ref error", __FUNCTION__);
+    *cachedObj = e->NewGlobalRef(obj.get());
+    if (*cachedObj == NULL) {
+        ALOGE("%s: global ref error", __FUNCTION__);
         return -1;
     }
-    e->DeleteLocalRef (obj);
     return 0;
 }
 
@@ -115,12 +109,9 @@
 *******************************************************************************/
 int nfc_jni_get_nfc_socket_handle (JNIEnv *e, jobject o)
 {
-    jclass c = NULL;
-    jfieldID f = 0;
-
-    c = e->GetObjectClass (o);
-    f = e->GetFieldID (c, "mHandle", "I");
-    return e->GetIntField (o, f);
+    ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+    jfieldID f = e->GetFieldID(c.get(), "mHandle", "I");
+    return e->GetIntField(o, f);
 }
 
 
@@ -137,13 +128,10 @@
 *******************************************************************************/
 struct nfc_jni_native_data* nfc_jni_get_nat(JNIEnv *e, jobject o)
 {
-   jclass c = NULL;
-   jfieldID f = 0;
-
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mNative", "I");
    /* Retrieve native structure address */
-   c = e->GetObjectClass(o);
-   f = e->GetFieldID(c, "mNative", "I");
-   return (struct nfc_jni_native_data*)e->GetIntField(o, f);
+   return (struct nfc_jni_native_data*) e->GetIntField(o, f);
 }
 
 
diff --git a/nci/jni/NfcJniUtil.h b/nci/jni/NfcJniUtil.h
index 8caa0b8..30c2046 100755
--- a/nci/jni/NfcJniUtil.h
+++ b/nci/jni/NfcJniUtil.h
@@ -15,6 +15,7 @@
  */
 
 #pragma once
+#undef LOG_TAG
 #define LOG_TAG "BrcmNfcJni"
 #include <JNIHelp.h>
 #include <jni.h>
@@ -131,6 +132,21 @@
 };
 
 
+class ScopedAttach {
+ public:
+  ScopedAttach(JavaVM* vm, JNIEnv** env) : vm_(vm) {
+    vm_->AttachCurrentThread(env, NULL);
+  }
+
+  ~ScopedAttach() {
+    vm_->DetachCurrentThread();
+  }
+
+ private:
+  JavaVM* vm_;
+};
+
+
 extern "C"
 {
     jint JNI_OnLoad(JavaVM *jvm, void *reserved);
diff --git a/nci/jni/NfcTag.cpp b/nci/jni/NfcTag.cpp
index b94355f..5c20452 100755
--- a/nci/jni/NfcTag.cpp
+++ b/nci/jni/NfcTag.cpp
@@ -20,6 +20,9 @@
 #include "OverrideLog.h"
 #include "NfcTag.h"
 #include "JavaClassConstants.h"
+#include <ScopedLocalRef.h>
+#include <ScopedPrimitiveArray.h>
+
 extern "C"
 {
     #include "rw_int.h"
@@ -491,63 +494,53 @@
 {
     static const char fn [] = "NfcTag::createNativeNfcTag";
     ALOGD ("%s: enter", fn);
-    JNIEnv* e = NULL;
-    jclass tag_cls = NULL;
-    jmethodID ctor = NULL;
-    jobject tag = NULL;
 
-    //acquire a pointer to the Java virtual machine
-    mNativeData->vm->AttachCurrentThread (&e, NULL);
-    if (e == NULL)
-    {
+    JNIEnv* e = NULL;
+    ScopedAttach attach(mNativeData->vm, &e);
+    if (e == NULL) {
         ALOGE("%s: jni env is null", fn);
-        goto TheEnd;
+        return;
     }
 
-    tag_cls = e->GetObjectClass (mNativeData->cached_NfcTag);
-    if (e->ExceptionCheck())
-    {
+    ScopedLocalRef<jclass> tag_cls(e, e->GetObjectClass(mNativeData->cached_NfcTag));
+    if (e->ExceptionCheck()) {
         e->ExceptionClear();
         ALOGE("%s: failed to get class", fn);
-        goto TheEnd;
+        return;
     }
 
     //create a new Java NativeNfcTag object
-    ctor = e->GetMethodID (tag_cls, "<init>", "()V");
-    tag = e->NewObject (tag_cls, ctor);
+    jmethodID ctor = e->GetMethodID(tag_cls.get(), "<init>", "()V");
+    ScopedLocalRef<jobject> tag(e, e->NewObject(tag_cls.get(), ctor));
 
     //fill NativeNfcTag's mProtocols, mTechList, mTechHandles, mTechLibNfcTypes
-    fillNativeNfcTagMembers1 (e, tag_cls, tag);
+    fillNativeNfcTagMembers1(e, tag_cls.get(), tag.get());
 
     //fill NativeNfcTag's members: mHandle, mConnectedTechnology
-    fillNativeNfcTagMembers2 (e, tag_cls, tag, activationData);
+    fillNativeNfcTagMembers2(e, tag_cls.get(), tag.get(), activationData);
 
     //fill NativeNfcTag's members: mTechPollBytes
-    fillNativeNfcTagMembers3 (e, tag_cls, tag, activationData);
+    fillNativeNfcTagMembers3(e, tag_cls.get(), tag.get(), activationData);
 
     //fill NativeNfcTag's members: mTechActBytes
-    fillNativeNfcTagMembers4 (e, tag_cls, tag, activationData);
+    fillNativeNfcTagMembers4(e, tag_cls.get(), tag.get(), activationData);
 
     //fill NativeNfcTag's members: mUid
-    fillNativeNfcTagMembers5 (e, tag_cls, tag, activationData);
+    fillNativeNfcTagMembers5(e, tag_cls.get(), tag.get(), activationData);
 
     if (mNativeData->tag != NULL) {
-        e->DeleteGlobalRef (mNativeData->tag);
+        e->DeleteGlobalRef(mNativeData->tag);
     }
-    mNativeData->tag = e->NewGlobalRef (tag);
+    mNativeData->tag = e->NewGlobalRef(tag.get());
 
     //notify NFC service about this new tag
     ALOGD ("%s: try notify nfc service", fn);
-    e->CallVoidMethod (mNativeData->manager, android::gCachedNfcManagerNotifyNdefMessageListeners, tag);
-    if (e->ExceptionCheck())
-    {
+    e->CallVoidMethod(mNativeData->manager, android::gCachedNfcManagerNotifyNdefMessageListeners, tag.get());
+    if (e->ExceptionCheck()) {
         e->ExceptionClear();
         ALOGE ("%s: fail notify nfc service", fn);
     }
-    e->DeleteLocalRef (tag);
 
-TheEnd:
-    mNativeData->vm->DetachCurrentThread ();
     ALOGD ("%s: exit", fn);
 }
 
@@ -568,36 +561,35 @@
 {
     static const char fn [] = "NfcTag::fillNativeNfcTagMembers1";
     ALOGD ("%s", fn);
-    jfieldID f = NULL;
 
     //create objects that represent NativeNfcTag's member variables
-    jintArray techList     = e->NewIntArray (mNumTechList);
-    jintArray handleList   = e->NewIntArray (mNumTechList);
-    jintArray typeList     = e->NewIntArray (mNumTechList);
+    ScopedLocalRef<jintArray> techList(e, e->NewIntArray(mNumTechList));
+    ScopedLocalRef<jintArray> handleList(e, e->NewIntArray(mNumTechList));
+    ScopedLocalRef<jintArray> typeList(e, e->NewIntArray(mNumTechList));
 
-    jint* technologies = e->GetIntArrayElements (techList,     NULL);
-    jint* handles      = e->GetIntArrayElements (handleList,   NULL);
-    jint* types        = e->GetIntArrayElements (typeList,     NULL);
-    for (int i = 0; i < mNumTechList; i++)
     {
-        mNativeData->tProtocols [i] = mTechLibNfcTypes [i];
-        mNativeData->handles [i] = mTechHandles [i];
-        technologies [i] = mTechList [i];
-        handles [i]      = mTechHandles [i];
-        types [i]        = mTechLibNfcTypes [i];
+        ScopedIntArrayRW technologies(e, techList.get());
+        ScopedIntArrayRW handles(e, handleList.get());
+        ScopedIntArrayRW types(e, typeList.get());
+        for (int i = 0; i < mNumTechList; i++) {
+            mNativeData->tProtocols [i] = mTechLibNfcTypes [i];
+            mNativeData->handles [i] = mTechHandles [i];
+            technologies [i] = mTechList [i];
+            handles [i]      = mTechHandles [i];
+            types [i]        = mTechLibNfcTypes [i];
+        }
     }
-    e->ReleaseIntArrayElements (techList,     technologies, 0);
-    e->ReleaseIntArrayElements (handleList,   handles,      0);
-    e->ReleaseIntArrayElements (typeList,     types,        0);
 
-    f = e->GetFieldID (tag_cls, "mTechList", "[I");
-    e->SetObjectField (tag, f, techList);
+    jfieldID f = NULL;
 
-    f = e->GetFieldID (tag_cls, "mTechHandles", "[I");
-    e->SetObjectField (tag, f, handleList);
+    f = e->GetFieldID(tag_cls, "mTechList", "[I");
+    e->SetObjectField(tag, f, techList.get());
 
-    f = e->GetFieldID (tag_cls, "mTechLibNfcTypes", "[I");
-    e->SetObjectField (tag, f, typeList);
+    f = e->GetFieldID(tag_cls, "mTechHandles", "[I");
+    e->SetObjectField(tag, f, handleList.get());
+
+    f = e->GetFieldID(tag_cls, "mTechLibNfcTypes", "[I");
+    e->SetObjectField(tag, f, typeList.get());
 }
 
 
@@ -617,14 +609,12 @@
 **
 *******************************************************************************/
 //fill NativeNfcTag's members: mHandle, mConnectedTechnology
-void NfcTag::fillNativeNfcTagMembers2 (JNIEnv* e, jclass tag_cls, jobject tag, tNFA_ACTIVATED& activationData)
+void NfcTag::fillNativeNfcTagMembers2 (JNIEnv* e, jclass tag_cls, jobject tag, tNFA_ACTIVATED& /*activationData*/)
 {
     static const char fn [] = "NfcTag::fillNativeNfcTagMembers2";
     ALOGD ("%s", fn);
-    jfieldID f = NULL;
-
-    f = e->GetFieldID (tag_cls, "mConnectedTechIndex", "I");
-    e->SetIntField (tag, f, (jint) 0);
+    jfieldID f = e->GetFieldID(tag_cls, "mConnectedTechIndex", "I");
+    e->SetIntField(tag, f, (jint) 0);
 }
 
 
@@ -646,9 +636,9 @@
 void NfcTag::fillNativeNfcTagMembers3 (JNIEnv* e, jclass tag_cls, jobject tag, tNFA_ACTIVATED& activationData)
 {
     static const char fn [] = "NfcTag::fillNativeNfcTagMembers3";
-    jfieldID f = NULL;
-    jbyteArray pollBytes = e->NewByteArray (0);
-    jobjectArray techPollBytes = e->NewObjectArray (mNumTechList, e->GetObjectClass(pollBytes), 0);
+    ScopedLocalRef<jbyteArray> pollBytes(e, e->NewByteArray(0));
+    ScopedLocalRef<jclass> byteArrayClass(e, e->GetObjectClass(pollBytes.get()));
+    ScopedLocalRef<jobjectArray> techPollBytes(e, e->NewObjectArray(mNumTechList, byteArrayClass.get(), 0));
     int len = 0;
 
     for (int i = 0; i < mNumTechList; i++)
@@ -661,9 +651,8 @@
         case NFC_DISCOVERY_TYPE_LISTEN_A:
         case NFC_DISCOVERY_TYPE_LISTEN_A_ACTIVE:
             ALOGD ("%s: tech A", fn);
-            pollBytes = e->NewByteArray (2);
-            e->SetByteArrayRegion (pollBytes, 0, 2,
-                    (jbyte*) mTechParams [i].param.pa.sens_res);
+            pollBytes.reset(e->NewByteArray(2));
+            e->SetByteArrayRegion(pollBytes.get(), 0, 2, (jbyte*) mTechParams [i].param.pa.sens_res);
             break;
 
         case NFC_DISCOVERY_TYPE_POLL_B:
@@ -680,11 +669,11 @@
                 ALOGD ("%s: tech B; TARGET_TYPE_ISO14443_3B", fn);
                 len = mTechParams [i].param.pb.sensb_res_len;
                 len = len - 4; //subtract 4 bytes for NFCID0 at byte 2 through 5
-                pollBytes = e->NewByteArray (len);
-                e->SetByteArrayRegion (pollBytes, 0, len, (jbyte*) (mTechParams [i].param.pb.sensb_res+4));
+                pollBytes.reset(e->NewByteArray(len));
+                e->SetByteArrayRegion(pollBytes.get(), 0, len, (jbyte*) (mTechParams [i].param.pb.sensb_res+4));
+            } else {
+                pollBytes.reset(e->NewByteArray(0));
             }
-            else
-                pollBytes = e->NewByteArray (0);
             break;
 
         case NFC_DISCOVERY_TYPE_POLL_F:
@@ -718,9 +707,9 @@
                     result [9] = (UINT8) systemCode;
                     ALOGD ("%s: tech F; sys code=0x%X 0x%X", fn, result [8], result [9]);
                 }
-                pollBytes = e->NewByteArray (len);
-                e->SetByteArrayRegion (pollBytes, 0, len, (jbyte*) result);
-			}
+                pollBytes.reset(e->NewByteArray(len));
+                e->SetByteArrayRegion(pollBytes.get(), 0, len, (jbyte*) result);
+            }
             break;
 
         case NFC_DISCOVERY_TYPE_POLL_ISO15693:
@@ -731,20 +720,20 @@
                 //iso 15693 Data Structure Format Identifier (DSF ID): 1 octet
                 //used by public API: NfcV.getDsfId(), NfcV.getResponseFlags();
                 uint8_t data [2]= {activationData.params.i93.afi, activationData.params.i93.dsfid};
-                pollBytes = e->NewByteArray (2);
-                e->SetByteArrayRegion (pollBytes, 0, 2, (jbyte *) data);
+                pollBytes.reset(e->NewByteArray(2));
+                e->SetByteArrayRegion(pollBytes.get(), 0, 2, (jbyte *) data);
             }
             break;
 
         default:
             ALOGE ("%s: tech unknown ????", fn);
-            pollBytes = e->NewByteArray(0);
+            pollBytes.reset(e->NewByteArray(0));
             break;
         } //switch: every type of technology
-        e->SetObjectArrayElement (techPollBytes, i, pollBytes);
+        e->SetObjectArrayElement(techPollBytes.get(), i, pollBytes.get());
     } //for: every technology in the array
-    f = e->GetFieldID (tag_cls, "mTechPollBytes", "[[B");
-    e->SetObjectField (tag, f, techPollBytes);
+    jfieldID f = e->GetFieldID(tag_cls, "mTechPollBytes", "[[B");
+    e->SetObjectField(tag, f, techPollBytes.get());
 }
 
 
@@ -766,11 +755,9 @@
 void NfcTag::fillNativeNfcTagMembers4 (JNIEnv* e, jclass tag_cls, jobject tag, tNFA_ACTIVATED& activationData)
 {
     static const char fn [] = "NfcTag::fillNativeNfcTagMembers4";
-    jfieldID f = NULL;
-    jbyteArray actBytes = e->NewByteArray (0);
-    jobjectArray techActBytes = e->NewObjectArray (mNumTechList, e->GetObjectClass(actBytes), 0);
-    jbyteArray uid = NULL;
-    int len = 0;
+    ScopedLocalRef<jbyteArray> actBytes(e, e->NewByteArray(0));
+    ScopedLocalRef<jclass> byteArrayClass(e, e->GetObjectClass(actBytes.get()));
+    ScopedLocalRef<jobjectArray> techActBytes(e, e->NewObjectArray(mNumTechList, byteArrayClass.get(), 0));
 
     for (int i = 0; i < mNumTechList; i++)
     {
@@ -780,18 +767,16 @@
         case NFC_PROTOCOL_T1T:
             {
                 ALOGD ("%s: T1T; tech A", fn);
-                actBytes = e->NewByteArray (1);
-                e->SetByteArrayRegion (actBytes, 0, 1,
-                        (jbyte*) &mTechParams [i].param.pa.sel_rsp);
+                actBytes.reset(e->NewByteArray(1));
+                e->SetByteArrayRegion(actBytes.get(), 0, 1, (jbyte*) &mTechParams [i].param.pa.sel_rsp);
             }
             break;
 
-        case NFC_PROTOCOL_T2T:
+        case NFC_PROTOCOL_T2T: // TODO: why is this code a duplicate of NFC_PROTOCOL_T1T?
             {
                 ALOGD ("%s: T2T; tech A", fn);
-                actBytes = e->NewByteArray (1);
-                e->SetByteArrayRegion (actBytes, 0, 1,
-                        (jbyte*) &mTechParams [i].param.pa.sel_rsp);
+                actBytes.reset(e->NewByteArray(1));
+                e->SetByteArrayRegion(actBytes.get(), 0, 1, (jbyte*) &mTechParams [i].param.pa.sel_rsp);
             }
             break;
 
@@ -799,7 +784,7 @@
             {
                 ALOGD ("%s: T3T; felica; tech F", fn);
                 //really, there is no data
-                actBytes = e->NewByteArray (0);
+                actBytes.reset(e->NewByteArray(0));
             }
             break;
 
@@ -819,14 +804,14 @@
                         {
                             tNFC_INTF_PA_ISO_DEP& pa_iso = activationData.activate_ntf.intf_param.intf_param.pa_iso;
                             ALOGD ("%s: T4T; ISO_DEP for tech A; copy historical bytes; len=%u", fn, pa_iso.his_byte_len);
-                            actBytes = e->NewByteArray (pa_iso.his_byte_len);
+                            actBytes.reset(e->NewByteArray(pa_iso.his_byte_len));
                             if (pa_iso.his_byte_len > 0)
-                                e->SetByteArrayRegion (actBytes, 0, pa_iso.his_byte_len, (jbyte*) (pa_iso.his_byte));
+                                e->SetByteArrayRegion(actBytes.get(), 0, pa_iso.his_byte_len, (jbyte*) (pa_iso.his_byte));
                         }
                         else
                         {
                             ALOGE ("%s: T4T; ISO_DEP for tech A; wrong interface=%u", fn, activationData.activate_ntf.intf_param.type);
-                            actBytes = e->NewByteArray (0);
+                            actBytes.reset(e->NewByteArray(0));
                         }
                     }
                     else if ( (mTechParams[i].mode == NFC_DISCOVERY_TYPE_POLL_B) ||
@@ -841,26 +826,26 @@
                         {
                             tNFC_INTF_PB_ISO_DEP& pb_iso = activationData.activate_ntf.intf_param.intf_param.pb_iso;
                             ALOGD ("%s: T4T; ISO_DEP for tech B; copy response bytes; len=%u", fn, pb_iso.hi_info_len);
-                            actBytes = e->NewByteArray (pb_iso.hi_info_len);
+                            actBytes.reset(e->NewByteArray(pb_iso.hi_info_len));
                             if (pb_iso.hi_info_len > 0)
-                                e->SetByteArrayRegion (actBytes, 0, pb_iso.hi_info_len, (jbyte*) (pb_iso.hi_info));
+                                e->SetByteArrayRegion(actBytes.get(), 0, pb_iso.hi_info_len, (jbyte*) (pb_iso.hi_info));
                         }
                         else
                         {
                             ALOGE ("%s: T4T; ISO_DEP for tech B; wrong interface=%u", fn, activationData.activate_ntf.intf_param.type);
-                            actBytes = e->NewByteArray (0);
+                            actBytes.reset(e->NewByteArray(0));
                         }
                     }
                 }
                 else if (mTechList [i] == TARGET_TYPE_ISO14443_3A) //is TagTechnology.NFC_A by Java API
                 {
                     ALOGD ("%s: T4T; tech A", fn);
-                    actBytes = e->NewByteArray (1);
-                    e->SetByteArrayRegion (actBytes, 0, 1, (jbyte*) &mTechParams [i].param.pa.sel_rsp);
+                    actBytes.reset(e->NewByteArray(1));
+                    e->SetByteArrayRegion(actBytes.get(), 0, 1, (jbyte*) &mTechParams [i].param.pa.sel_rsp);
                 }
                 else
                 {
-                    actBytes = e->NewByteArray (0);
+                    actBytes.reset(e->NewByteArray(0));
                 }
             } //case NFC_PROTOCOL_ISO_DEP: //t4t
             break;
@@ -872,20 +857,20 @@
                 //iso 15693 Data Structure Format Identifier (DSF ID): 1 octet
                 //used by public API: NfcV.getDsfId(), NfcV.getResponseFlags();
                 uint8_t data [2]= {activationData.params.i93.afi, activationData.params.i93.dsfid};
-                actBytes = e->NewByteArray (2);
-                e->SetByteArrayRegion (actBytes, 0, 2, (jbyte *) data);
+                actBytes.reset(e->NewByteArray(2));
+                e->SetByteArrayRegion(actBytes.get(), 0, 2, (jbyte *) data);
             }
             break;
 
         default:
             ALOGD ("%s: tech unknown ????", fn);
-            actBytes = e->NewByteArray (0);
+            actBytes.reset(e->NewByteArray(0));
             break;
         }//switch
-        e->SetObjectArrayElement (techActBytes, i, actBytes);
+        e->SetObjectArrayElement(techActBytes.get(), i, actBytes.get());
     } //for: every technology in the array
-    f = e->GetFieldID (tag_cls, "mTechActBytes", "[[B");
-    e->SetObjectField (tag, f, techActBytes);
+    jfieldID f = e->GetFieldID (tag_cls, "mTechActBytes", "[[B");
+    e->SetObjectField(tag, f, techActBytes.get());
 }
 
 
@@ -907,17 +892,16 @@
 void NfcTag::fillNativeNfcTagMembers5 (JNIEnv* e, jclass tag_cls, jobject tag, tNFA_ACTIVATED& activationData)
 {
     static const char fn [] = "NfcTag::fillNativeNfcTagMembers5";
-    jfieldID f = NULL;
     int len = 0;
-    jbyteArray uid = NULL;
+    ScopedLocalRef<jbyteArray> uid(e, NULL);
 
     switch (mTechParams [0].mode)
     {
     case NFC_DISCOVERY_TYPE_POLL_KOVIO:
         ALOGD ("%s: Kovio", fn);
         len = mTechParams [0].param.pk.uid_len;
-        uid = e->NewByteArray (len);
-        e->SetByteArrayRegion (uid, 0, len,
+        uid.reset(e->NewByteArray(len));
+        e->SetByteArrayRegion(uid.get(), 0, len,
                 (jbyte*) &mTechParams [0].param.pk.uid);
         break;
 
@@ -927,8 +911,8 @@
     case NFC_DISCOVERY_TYPE_LISTEN_A_ACTIVE:
         ALOGD ("%s: tech A", fn);
         len = mTechParams [0].param.pa.nfcid1_len;
-        uid = e->NewByteArray (len);
-        e->SetByteArrayRegion (uid, 0, len,
+        uid.reset(e->NewByteArray(len));
+        e->SetByteArrayRegion(uid.get(), 0, len,
                 (jbyte*) &mTechParams [0].param.pa.nfcid1);
         break;
 
@@ -937,8 +921,8 @@
     case NFC_DISCOVERY_TYPE_LISTEN_B:
     case NFC_DISCOVERY_TYPE_LISTEN_B_PRIME:
         ALOGD ("%s: tech B", fn);
-        uid = e->NewByteArray (NFC_NFCID0_MAX_LEN);
-        e->SetByteArrayRegion (uid, 0, NFC_NFCID0_MAX_LEN,
+        uid.reset(e->NewByteArray(NFC_NFCID0_MAX_LEN));
+        e->SetByteArrayRegion(uid.get(), 0, NFC_NFCID0_MAX_LEN,
                 (jbyte*) &mTechParams [0].param.pb.nfcid0);
         break;
 
@@ -947,8 +931,8 @@
     case NFC_DISCOVERY_TYPE_LISTEN_F:
     case NFC_DISCOVERY_TYPE_LISTEN_F_ACTIVE:
         ALOGD ("%s: tech F", fn);
-        uid = e->NewByteArray (NFC_NFCID2_LEN);
-        e->SetByteArrayRegion (uid, 0, NFC_NFCID2_LEN,
+        uid.reset(e->NewByteArray(NFC_NFCID2_LEN));
+        e->SetByteArrayRegion(uid.get(), 0, NFC_NFCID2_LEN,
                 (jbyte*) &mTechParams [0].param.pf.nfcid2);
         break;
 
@@ -959,18 +943,18 @@
             jbyte data [I93_UID_BYTE_LEN];  //8 bytes
             for (int i=0; i<I93_UID_BYTE_LEN; ++i) //reverse the ID
                 data[i] = activationData.params.i93.uid [I93_UID_BYTE_LEN - i - 1];
-            uid = e->NewByteArray (I93_UID_BYTE_LEN);
-            e->SetByteArrayRegion (uid, 0, I93_UID_BYTE_LEN, data);
+            uid.reset(e->NewByteArray(I93_UID_BYTE_LEN));
+            e->SetByteArrayRegion(uid.get(), 0, I93_UID_BYTE_LEN, data);
         }
         break;
 
     default:
         ALOGE ("%s: tech unknown ????", fn);
-        uid = e->NewByteArray (0);
+        uid.reset(e->NewByteArray(0));
         break;
-    } //if
-    f = e->GetFieldID(tag_cls, "mUid", "[B");
-    e->SetObjectField(tag, f, uid);
+    }
+    jfieldID f = e->GetFieldID(tag_cls, "mUid", "[B");
+    e->SetObjectField(tag, f, uid.get());
 }
 
 
@@ -1322,4 +1306,3 @@
         }
     }
 }
-
diff --git a/nci/jni/PeerToPeer.cpp b/nci/jni/PeerToPeer.cpp
index 7994e2a..3a73f7a 100644
--- a/nci/jni/PeerToPeer.cpp
+++ b/nci/jni/PeerToPeer.cpp
@@ -23,6 +23,7 @@
 #include "llcp_defs.h"
 #include "config.h"
 #include "JavaClassConstants.h"
+#include <ScopedLocalRef.h>
 
 using namespace android;
 
@@ -55,7 +56,6 @@
                         | NFA_TECHNOLOGY_MASK_F_ACTIVE),
     mNextJniHandle (1)
 {
-    unsigned long num = 0;
     memset (mServers, 0, sizeof(mServers));
     memset (mClients, 0, sizeof(mClients));
 }
@@ -202,9 +202,7 @@
 {
     static const char fn [] = "PeerToPeer::registerServer";
     ALOGD ("%s: enter; service name: %s  JNI handle: %u", fn, serviceName, jniHandle);
-    tNFA_STATUS     stat  = NFA_STATUS_OK;
     sp<P2pServer>   pSrv = NULL;
-    UINT8           serverSap = NFA_P2P_ANY_SAP;
 
     mMutex.lock();
     // Check if already registered
@@ -293,18 +291,14 @@
 {
     static const char fn [] = "PeerToPeer::llcpActivatedHandler";
     ALOGD ("%s: enter", fn);
-    JNIEnv* e = NULL;
-    jclass tag_cls = NULL;
-    jobject tag = NULL;
-    jmethodID ctor = 0;
-    jfieldID f = 0;
 
     //no longer need to receive NDEF message from a tag
     android::nativeNfcTag_deregisterNdefTypeHandler ();
 
     mRemoteWKS = activated.remote_wks;
 
-    nat->vm->AttachCurrentThread (&e, NULL);
+    JNIEnv* e = NULL;
+    ScopedAttach attach(nat->vm, &e);
     if (e == NULL)
     {
         ALOGE ("%s: jni env is null", fn);
@@ -312,57 +306,47 @@
     }
 
     ALOGD ("%s: get object class", fn);
-    tag_cls = e->GetObjectClass (nat->cached_P2pDevice);
-    if (e->ExceptionCheck())
-    {
+    ScopedLocalRef<jclass> tag_cls(e, e->GetObjectClass(nat->cached_P2pDevice));
+    if (e->ExceptionCheck()) {
         e->ExceptionClear();
         ALOGE ("%s: fail get p2p device", fn);
-        goto TheEnd;
+        return;
     }
 
     ALOGD ("%s: instantiate", fn);
     /* New target instance */
-    ctor = e->GetMethodID (tag_cls, "<init>", "()V");
-    tag = e->NewObject (tag_cls, ctor);
+    jmethodID ctor = e->GetMethodID(tag_cls.get(), "<init>", "()V");
+    ScopedLocalRef<jobject> tag(e, e->NewObject(tag_cls.get(), ctor));
 
     /* Set P2P Target mode */
-    f = e->GetFieldID (tag_cls, "mMode", "I");
+    jfieldID f = e->GetFieldID(tag_cls.get(), "mMode", "I");
 
-    if (activated.is_initiator == TRUE)
-    {
+    if (activated.is_initiator == TRUE) {
         ALOGD ("%s: p2p initiator", fn);
-        e->SetIntField (tag, f, (jint) MODE_P2P_INITIATOR);
-    }
-    else
-    {
+        e->SetIntField(tag.get(), f, (jint) MODE_P2P_INITIATOR);
+    } else {
         ALOGD ("%s: p2p target", fn);
-        e->SetIntField (tag, f, (jint) MODE_P2P_TARGET);
+        e->SetIntField(tag.get(), f, (jint) MODE_P2P_TARGET);
     }
 
     /* Set tag handle */
-    f = e->GetFieldID (tag_cls, "mHandle", "I");
-    e->SetIntField (tag, f, (jint) 0x1234); // ?? This handle is not used for anything
+    f = e->GetFieldID(tag_cls.get(), "mHandle", "I");
+    e->SetIntField(tag.get(), f, (jint) 0x1234); // ?? This handle is not used for anything
 
-    if (nat->tag != NULL)
-    {
-        e->DeleteGlobalRef (nat->tag);
+    if (nat->tag != NULL) {
+        e->DeleteGlobalRef(nat->tag);
     }
-    nat->tag = e->NewGlobalRef (tag);
+    nat->tag = e->NewGlobalRef(tag.get());
 
     ALOGD ("%s: notify nfc service", fn);
 
     /* Notify manager that new a P2P device was found */
-    e->CallVoidMethod (nat->manager, android::gCachedNfcManagerNotifyLlcpLinkActivation, tag);
-    if (e->ExceptionCheck())
-    {
+    e->CallVoidMethod(nat->manager, android::gCachedNfcManagerNotifyLlcpLinkActivation, tag.get());
+    if (e->ExceptionCheck()) {
         e->ExceptionClear();
         ALOGE ("%s: fail notify", fn);
     }
 
-    e->DeleteLocalRef (tag);
-
-TheEnd:
-    nat->vm->DetachCurrentThread ();
     ALOGD ("%s: exit", fn);
 }
 
@@ -378,13 +362,13 @@
 ** Returns:         None
 **
 *******************************************************************************/
-void PeerToPeer::llcpDeactivatedHandler (nfc_jni_native_data* nat, tNFA_LLCP_DEACTIVATED& deactivated)
+void PeerToPeer::llcpDeactivatedHandler (nfc_jni_native_data* nat, tNFA_LLCP_DEACTIVATED& /*deactivated*/)
 {
     static const char fn [] = "PeerToPeer::llcpDeactivatedHandler";
     ALOGD ("%s: enter", fn);
-    JNIEnv* e = NULL;
 
-    nat->vm->AttachCurrentThread (&e, NULL);
+    JNIEnv* e = NULL;
+    ScopedAttach attach(nat->vm, &e);
     if (e == NULL)
     {
         ALOGE ("%s: jni env is null", fn);
@@ -400,8 +384,6 @@
         ALOGE ("%s: fail notify", fn);
     }
 
-    nat->vm->DetachCurrentThread ();
-
     //let the tag-reading code handle NDEF data event
     android::nativeNfcTag_registerNdefTypeHandler ();
     ALOGD ("%s: exit", fn);
@@ -424,10 +406,6 @@
 bool PeerToPeer::accept (tJNI_HANDLE serverJniHandle, tJNI_HANDLE connJniHandle, int maxInfoUnit, int recvWindow)
 {
     static const char fn [] = "PeerToPeer::accept";
-    tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
-    sp<NfaConn>     *pConn = NULL;
-    bool        stat = false;
-    int         ii = 0;
     sp<P2pServer> pSrv = NULL;
 
     ALOGD ("%s: enter; server jni handle: %u; conn jni handle: %u; maxInfoUnit: %d; recvWindow: %d", fn,
@@ -565,11 +543,10 @@
 void PeerToPeer::removeConn(tJNI_HANDLE jniHandle)
 {
     static const char fn[] = "PeerToPeer::removeConn";
-    int ii = 0, jj = 0;
 
     AutoMutex mutex(mMutex);
     // If the connection is a for a client, delete the client itself
-    for (ii = 0; ii < sMax; ii++)
+    for (size_t ii = 0; ii < sMax; ii++)
     {
         if ((mClients[ii] != NULL) && (mClients[ii]->mClientConn->mJniHandle == jniHandle))
         {
@@ -583,7 +560,7 @@
     }
 
     // If the connection is for a server, just delete the connection
-    for (ii = 0; ii < sMax; ii++)
+    for (size_t ii = 0; ii < sMax; ii++)
     {
         if (mServers[ii] != NULL)
         {
@@ -781,11 +758,9 @@
 *******************************************************************************/
 sp<NfaConn> PeerToPeer::findConnection (tNFA_HANDLE nfaConnHandle)
 {
-    int ii = 0, jj = 0;
-
     AutoMutex mutex(mMutex);
     // First, look through all the client control blocks
-    for (ii = 0; ii < sMax; ii++)
+    for (size_t ii = 0; ii < sMax; ii++)
     {
         if ( (mClients[ii] != NULL)
            && (mClients[ii]->mClientConn->mNfaConnHandle == nfaConnHandle) ) {
@@ -794,7 +769,7 @@
     }
 
     // Not found yet. Look through all the server control blocks
-    for (ii = 0; ii < sMax; ii++)
+    for (size_t ii = 0; ii < sMax; ii++)
     {
         if (mServers[ii] != NULL)
         {
@@ -822,11 +797,9 @@
 *******************************************************************************/
 sp<NfaConn> PeerToPeer::findConnection (tJNI_HANDLE jniHandle)
 {
-    int ii = 0, jj = 0;
-
     AutoMutex mutex(mMutex);
     // First, look through all the client control blocks
-    for (ii = 0; ii < sMax; ii++)
+    for (size_t ii = 0; ii < sMax; ii++)
     {
         if ( (mClients[ii] != NULL)
           && (mClients[ii]->mClientConn->mJniHandle == jniHandle) ) {
@@ -835,7 +808,7 @@
     }
 
     // Not found yet. Look through all the server control blocks
-    for (ii = 0; ii < sMax; ii++)
+    for (size_t ii = 0; ii < sMax; ii++)
     {
         if (mServers[ii] != NULL)
         {
@@ -1142,7 +1115,6 @@
 {
     static const char fn [] = "PeerToPeer::handleNfcOnOff";
     ALOGD ("%s: enter; is on=%u", fn, isOn);
-    tNFA_STATUS stat = NFA_STATUS_FAILED;
 
     mIsP2pListening = false;            // In both cases, P2P will not be listening
 
@@ -1155,10 +1127,8 @@
     }
     else
     {
-        int ii = 0, jj = 0;
-
         // Disconnect through all the clients
-        for (ii = 0; ii < sMax; ii++)
+        for (size_t ii = 0; ii < sMax; ii++)
         {
             if (mClients[ii] != NULL)
             {
@@ -1183,7 +1153,7 @@
         } //loop
 
         // Now look through all the server control blocks
-        for (ii = 0; ii < sMax; ii++)
+        for (size_t ii = 0; ii < sMax; ii++)
         {
             if (mServers[ii] != NULL)
             {
@@ -1515,7 +1485,7 @@
 ** Returns:         None
 **
 *******************************************************************************/
-void PeerToPeer::connectionEventHandler (UINT8 event, tNFA_CONN_EVT_DATA* eventData)
+void PeerToPeer::connectionEventHandler (UINT8 event, tNFA_CONN_EVT_DATA* /*eventData*/)
 {
     switch (event)
     {
@@ -1837,4 +1807,3 @@
     mRemoteRecvWindow (0)
 {
 }
-
diff --git a/nci/jni/RouteDataSet.cpp b/nci/jni/RouteDataSet.cpp
index 1458776..e0a918f 100644
--- a/nci/jni/RouteDataSet.cpp
+++ b/nci/jni/RouteDataSet.cpp
@@ -528,6 +528,7 @@
                 ALOGD ("%s: ee h=0x%X; protocol=0x%X", fn, proto->mNfaEeHandle, proto->mProtocol);
             }
             break;
+        // TODO: RouteData::TechnologyRoute isn't handled --- bug?
         }
     }
 
diff --git a/nci/jni/SecureElement.cpp b/nci/jni/SecureElement.cpp
index 3c9256b..780b069 100755
--- a/nci/jni/SecureElement.cpp
+++ b/nci/jni/SecureElement.cpp
@@ -20,6 +20,7 @@
  */
 #include <semaphore.h>
 #include <errno.h>
+#include <ScopedLocalRef.h>
 #include "OverrideLog.h"
 #include "SecureElement.h"
 #include "config.h"
@@ -149,7 +150,6 @@
 {
     static const char fn [] = "SecureElement::initialize";
     tNFA_STATUS nfaStat;
-    UINT8 xx = 0, yy = 0;
     unsigned long num = 0;
 
     ALOGD ("%s: enter", fn);
@@ -201,7 +201,7 @@
     }
 
     // If the controller has an HCI Network, register for that
-    for (xx = 0; xx < mActualNumEe; xx++)
+    for (size_t xx = 0; xx < mActualNumEe; xx++)
     {
         if ((mEeInfo[xx].num_interface > 0) && (mEeInfo[xx].ee_interface[0] == NCI_NFCEE_INTERFACE_HCI_ACCESS) )
         {
@@ -281,7 +281,6 @@
     static const char fn [] = "SecureElement::getEeInfo";
     ALOGD ("%s: enter; mbNewEE=%d, mActualNumEe=%d", fn, mbNewEE, mActualNumEe);
     tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
-    UINT8 xx = 0, yy = 0;
 
     // If mbNewEE is true then there is new EE info.
     if (mbNewEE)
@@ -309,7 +308,7 @@
                           fn, xx, mEeInfo[xx].ee_handle, eeStatusToString(mEeInfo[xx].ee_status), mEeInfo[xx].num_interface,
                           mEeInfo[xx].ee_interface[0], mEeInfo[xx].ee_interface[1], mEeInfo[xx].num_tlvs);
 
-                    for (yy = 0; yy < mEeInfo[xx].num_tlvs; yy++)
+                    for (size_t yy = 0; yy < mEeInfo[xx].num_tlvs; yy++)
                     {
                         ALOGD ("%s: EE[%u] TLV[%u]  Tag: 0x%02x  Len: %u  Values[]: 0x%02x  0x%02x  0x%02x ...",
                               fn, xx, yy, mEeInfo[xx].ee_tlv[yy].tag, mEeInfo[xx].ee_tlv[yy].len, mEeInfo[xx].ee_tlv[yy].info[0],
@@ -404,7 +403,6 @@
     ALOGD ("%s: enter", fn);
     if (mNumEePresent == 0)
         return NULL;
-    jintArray list = NULL;
 
     if (!mIsInit)
     {
@@ -416,7 +414,7 @@
     if (! getEeInfo())
         return (NULL);
 
-    list = e->NewIntArray (mNumEePresent); //allocate array
+    jintArray list = e->NewIntArray (mNumEePresent); //allocate array
     jint jj = 0;
     int cnt = 0;
     for (int ii = 0; ii < mActualNumEe && cnt < mNumEePresent; ii++)
@@ -430,7 +428,6 @@
         jj = mEeInfo[ii].ee_handle & ~NFA_HANDLE_GROUP_EE;
         e->SetIntArrayRegion (list, cnt++, 1, &jj);
     }
-    //e->DeleteLocalRef (list);
 
     ALOGD("%s: exit", fn);
     return list;
@@ -553,7 +550,6 @@
 {
     static const char fn [] = "SecureElement::deactivate";
     tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
-    int numDeactivatedEe = 0;
     bool retval = false;
 
     ALOGD ("%s: enter; seID=0x%X, mActiveEeHandle=0x%X", fn, seID, mActiveEeHandle);
@@ -603,41 +599,37 @@
     static const char fn [] = "SecureElement::notifyTransactionListenersOfAid";
     ALOGD ("%s: enter; aid len=%u", fn, aidBufferLen);
 
-    if (aidBufferLen == 0)
-    	return;
+    if (aidBufferLen == 0) {
+        return;
+    }
 
-    jobject tlvJavaArray = NULL;
     JNIEnv* e = NULL;
-    UINT8* tlv = 0;
-    const UINT16 tlvMaxLen = aidBufferLen + 10;
-    UINT16 tlvActualLen = 0;
-    bool stat = false;
-
-    mNativeData->vm->AttachCurrentThread (&e, NULL);
+    ScopedAttach attach(mNativeData->vm, &e);
     if (e == NULL)
     {
         ALOGE ("%s: jni env is null", fn);
         return;
     }
 
-    tlv = new UINT8 [tlvMaxLen];
+    const UINT16 tlvMaxLen = aidBufferLen + 10;
+    UINT8* tlv = new UINT8 [tlvMaxLen];
     if (tlv == NULL)
     {
         ALOGE ("%s: fail allocate tlv", fn);
-        goto TheEnd;
+        return;
     }
 
     memcpy (tlv, aidBuffer, aidBufferLen);
-    tlvActualLen = aidBufferLen;
+    UINT16 tlvActualLen = aidBufferLen;
 
-    tlvJavaArray = e->NewByteArray (tlvActualLen);
-    if (tlvJavaArray == NULL)
+    ScopedLocalRef<jobject> tlvJavaArray(e, e->NewByteArray(tlvActualLen));
+    if (tlvJavaArray.get() == NULL)
     {
         ALOGE ("%s: fail allocate array", fn);
         goto TheEnd;
     }
 
-    e->SetByteArrayRegion ((jbyteArray)tlvJavaArray, 0, tlvActualLen, (jbyte *)tlv);
+    e->SetByteArrayRegion ((jbyteArray)tlvJavaArray.get(), 0, tlvActualLen, (jbyte *)tlv);
     if (e->ExceptionCheck())
     {
         e->ExceptionClear();
@@ -645,7 +637,7 @@
         goto TheEnd;
     }
 
-    e->CallVoidMethod (mNativeData->manager, android::gCachedNfcManagerNotifyTransactionListeners, tlvJavaArray);
+    e->CallVoidMethod (mNativeData->manager, android::gCachedNfcManagerNotifyTransactionListeners, tlvJavaArray.get());
     if (e->ExceptionCheck())
     {
         e->ExceptionClear();
@@ -654,9 +646,6 @@
     }
 
 TheEnd:
-    if (tlvJavaArray)
-        e->DeleteLocalRef (tlvJavaArray);
-    mNativeData->vm->DetachCurrentThread ();
     delete [] tlv;
     ALOGD ("%s: exit", fn);
 }
@@ -1022,11 +1011,11 @@
 *******************************************************************************/
 void SecureElement::notifyListenModeState (bool isActivated) {
     static const char fn [] = "SecureElement::notifyListenMode";
-    JNIEnv *e = NULL;
 
     ALOGD ("%s: enter; listen mode active=%u", fn, isActivated);
-    mNativeData->vm->AttachCurrentThread (&e, NULL);
 
+    JNIEnv* e = NULL;
+    ScopedAttach attach(mNativeData->vm, &e);
     if (e == NULL)
     {
         ALOGE ("%s: jni env is null", fn);
@@ -1047,7 +1036,6 @@
         ALOGE ("%s: fail notify", fn);
     }
 
-    mNativeData->vm->DetachCurrentThread ();
     ALOGD ("%s: exit", fn);
 }
 
@@ -1064,11 +1052,10 @@
 void SecureElement::notifyRfFieldEvent (bool isActive)
 {
     static const char fn [] = "SecureElement::notifyRfFieldEvent";
-    JNIEnv *e = NULL;
-
     ALOGD ("%s: enter; is active=%u", fn, isActive);
-    mNativeData->vm->AttachCurrentThread (&e, NULL);
 
+    JNIEnv* e = NULL;
+    ScopedAttach attach(mNativeData->vm, &e);
     if (e == NULL)
     {
         ALOGE ("%s: jni env is null", fn);
@@ -1096,7 +1083,6 @@
         e->ExceptionClear();
         ALOGE ("%s: fail notify", fn);
     }
-    mNativeData->vm->DetachCurrentThread ();
     ALOGD ("%s: exit", fn);
 }
 
@@ -1149,9 +1135,9 @@
     static const char fn [] = "SecureElement::getUiccId";
     ALOGD ("%s: ee h=0x%X", fn, eeHandle);
     bool retval = false;
-    JNIEnv* e = NULL;
 
-    mNativeData->vm->AttachCurrentThread (&e, NULL);
+    JNIEnv* e = NULL;
+    ScopedAttach attach(mNativeData->vm, &e);
     if (e == NULL)
     {
         ALOGE ("%s: jni env is null", fn);
@@ -1161,8 +1147,9 @@
     findUiccByHandle (eeHandle);
     //cannot get UID from the stack; nothing to do
 
-TheEnd:
-    mNativeData->vm->DetachCurrentThread ();
+    // TODO: uid is unused --- bug?
+
+    // TODO: retval is always false --- bug?
     ALOGD ("%s: exit; ret=%u", fn, retval);
     return retval;
 }
@@ -1184,10 +1171,9 @@
     static const char fn [] = "SecureElement::getTechnologyList";
     ALOGD ("%s: ee h=0x%X", fn, eeHandle);
     bool retval = false;
-    JNIEnv* e = NULL;
-    jint theList = 0;
 
-    mNativeData->vm->AttachCurrentThread (&e, NULL);
+    JNIEnv* e = NULL;
+    ScopedAttach attach(mNativeData->vm, &e);
     if (e == NULL)
     {
         ALOGE ("%s: jni env is null", fn);
@@ -1196,6 +1182,8 @@
 
     tNFA_EE_DISCOVER_INFO *pUICC = findUiccByHandle (eeHandle);
 
+    // TODO: theList is written but not set --- bug?
+    jint theList = 0;
     if (pUICC->la_protocol != 0)
         theList = TARGET_TYPE_ISO14443_3A;
     else if (pUICC->lb_protocol != 0)
@@ -1207,8 +1195,9 @@
     else
         theList = TARGET_TYPE_UNKNOWN;
 
-TheEnd:
-    mNativeData->vm->DetachCurrentThread ();
+    // TODO: techList is neither read nor written --- bug?
+
+    // TODO: retval is always false --- bug?
     ALOGD ("%s: exit; ret=%u", fn, retval);
     return retval;
 }
@@ -1228,7 +1217,6 @@
 {
     static const char fn [] = "SecureElement::adjustRoutes";
     ALOGD ("%s: enter; selection=%u", fn, selection);
-    tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
     RouteDataSet::Database* db = mRouteDataSet.getDatabase (RouteDataSet::DefaultRouteDatabase);
 
     if (selection == SecElemRoute)
@@ -2045,7 +2033,7 @@
 ** Returns:         None
 **
 *******************************************************************************/
-void SecureElement::connectionEventHandler (UINT8 event, tNFA_CONN_EVT_DATA* eventData)
+void SecureElement::connectionEventHandler (UINT8 event, tNFA_CONN_EVT_DATA* /*eventData*/)
 {
     switch (event)
     {
@@ -2186,4 +2174,3 @@
     ALOGD ("SecureElement::isBusy: %u", retval);
     return retval;
 }
-
diff --git a/nxp/jni/Android.mk b/nxp/jni/Android.mk
index 8ae792a..8b73709 100644
--- a/nxp/jni/Android.mk
+++ b/nxp/jni/Android.mk
@@ -18,7 +18,8 @@
 LOCAL_C_INCLUDES += \
     $(JNI_H_INCLUDE) \
     external/libnfc-nxp/src \
-    external/libnfc-nxp/inc
+    external/libnfc-nxp/inc \
+    libcore/include
 
 LOCAL_SHARED_LIBRARIES := \
     libnativehelper \
diff --git a/nxp/jni/com_android_nfc.cpp b/nxp/jni/com_android_nfc.cpp
index d794d6e..2852706 100644
--- a/nxp/jni/com_android_nfc.cpp
+++ b/nxp/jni/com_android_nfc.cpp
@@ -20,6 +20,7 @@
 #include "com_android_nfc.h"
 #include "com_android_nfc_list.h"
 #include "phLibNfcStatus.h"
+#include <ScopedLocalRef.h>
 
 /*
  * JNI Initialization
@@ -28,7 +29,7 @@
 {
    JNIEnv *e;
 
-   ALOGD("NFC Service : loading JNI\n");
+   ALOGI("NFC Service: loading nxp JNI");
 
    // Check JNI version
    if(jvm->GetEnv((void **)&e, JNI_VERSION_1_6))
@@ -128,50 +129,35 @@
 int nfc_jni_cache_object(JNIEnv *e, const char *clsname,
    jobject *cached_obj)
 {
-   jclass cls;
-   jobject obj;
-   jmethodID ctor;
-
-   cls = e->FindClass(clsname);
-   if(cls == NULL)
-   {
-      return -1;
+   ScopedLocalRef<jclass> cls(e, e->FindClass(clsname));
+   if (cls.get() == NULL) {
       ALOGD("Find class error\n");
-   }
-
-
-   ctor = e->GetMethodID(cls, "<init>", "()V");
-
-   obj = e->NewObject(cls, ctor);
-   if(obj == NULL)
-   {
       return -1;
-      ALOGD("Create object error\n");
    }
 
-   *cached_obj = e->NewGlobalRef(obj);
-   if(*cached_obj == NULL)
-   {
-      e->DeleteLocalRef(obj);
+   jmethodID ctor = e->GetMethodID(cls.get(), "<init>", "()V");
+   ScopedLocalRef<jobject> obj(e, e->NewObject(cls.get(), ctor));
+   if (obj.get() == NULL) {
+      ALOGD("Create object error\n");
+      return -1;
+   }
+
+   *cached_obj = e->NewGlobalRef(obj.get());
+   if (*cached_obj == NULL) {
       ALOGD("Global ref error\n");
       return -1;
    }
 
-   e->DeleteLocalRef(obj);
-
    return 0;
 }
 
 
 struct nfc_jni_native_data* nfc_jni_get_nat(JNIEnv *e, jobject o)
 {
-   jclass c;
-   jfieldID f;
-
    /* Retrieve native structure address */
-   c = e->GetObjectClass(o);
-   f = e->GetFieldID(c, "mNative", "I");
-   return (struct nfc_jni_native_data*)e->GetIntField(o, f);
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mNative", "I");
+   return (struct nfc_jni_native_data*) e->GetIntField(o, f);
 }
 
 struct nfc_jni_native_data* nfc_jni_get_nat_ext(JNIEnv *e)
@@ -233,54 +219,39 @@
 }
 
    return nfc_jni_native_monitor;
-} 
+}
 
 nfc_jni_native_monitor_t* nfc_jni_get_monitor(void)
 {
    return nfc_jni_native_monitor;
 }
-   
+
 
 phLibNfc_Handle nfc_jni_get_p2p_device_handle(JNIEnv *e, jobject o)
 {
-   jclass c;
-   jfieldID f;
-
-   c = e->GetObjectClass(o);
-   f = e->GetFieldID(c, "mHandle", "I");
-
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mHandle", "I");
    return e->GetIntField(o, f);
 }
 
 jshort nfc_jni_get_p2p_device_mode(JNIEnv *e, jobject o)
 {
-   jclass c;
-   jfieldID f;
-
-   c = e->GetObjectClass(o);
-   f = e->GetFieldID(c, "mMode", "S");
-
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mMode", "S");
    return e->GetShortField(o, f);
 }
 
 
 int nfc_jni_get_connected_tech_index(JNIEnv *e, jobject o)
 {
-
-   jclass c;
-   jfieldID f;
-
-   c = e->GetObjectClass(o);
-   f = e->GetFieldID(c, "mConnectedTechIndex", "I");
-
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mConnectedTechIndex", "I");
    return e->GetIntField(o, f);
 
 }
 
 jint nfc_jni_get_connected_technology(JNIEnv *e, jobject o)
 {
-   jclass c;
-   jfieldID f;
    int connectedTech = -1;
 
    int connectedTechIndex = nfc_jni_get_connected_tech_index(e,o);
@@ -301,62 +272,43 @@
 
 jint nfc_jni_get_connected_technology_libnfc_type(JNIEnv *e, jobject o)
 {
-   jclass c;
-   jfieldID f;
    jint connectedLibNfcType = -1;
 
    int connectedTechIndex = nfc_jni_get_connected_tech_index(e,o);
-   c = e->GetObjectClass(o);
-   f = e->GetFieldID(c, "mTechLibNfcTypes", "[I");
-   jintArray libNfcTypes =  (jintArray) e->GetObjectField(o, f);
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mTechLibNfcTypes", "[I");
+   ScopedLocalRef<jintArray> libNfcTypes(e, (jintArray) e->GetObjectField(o, f));
 
-   if ((connectedTechIndex != -1) && (libNfcTypes != NULL) &&
-           (connectedTechIndex < e->GetArrayLength(libNfcTypes))) {
-       jint* types = e->GetIntArrayElements(libNfcTypes, 0);
+   if ((connectedTechIndex != -1) && (libNfcTypes.get() != NULL) &&
+           (connectedTechIndex < e->GetArrayLength(libNfcTypes.get()))) {
+       jint* types = e->GetIntArrayElements(libNfcTypes.get(), 0);
        if (types != NULL) {
            connectedLibNfcType = types[connectedTechIndex];
-           e->ReleaseIntArrayElements(libNfcTypes, types, JNI_ABORT);
+           e->ReleaseIntArrayElements(libNfcTypes.get(), types, JNI_ABORT);
        }
    }
    return connectedLibNfcType;
-
 }
 
 phLibNfc_Handle nfc_jni_get_connected_handle(JNIEnv *e, jobject o)
 {
-   jclass c;
-   jfieldID f;
-
-   c = e->GetObjectClass(o);
-   f = e->GetFieldID(c, "mConnectedHandle", "I");
-
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mConnectedHandle", "I");
    return e->GetIntField(o, f);
 }
 
 phLibNfc_Handle nfc_jni_get_nfc_socket_handle(JNIEnv *e, jobject o)
 {
-   jclass c;
-   jfieldID f;
-
-   c = e->GetObjectClass(o);
-   f = e->GetFieldID(c, "mHandle", "I");
-
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mHandle", "I");
    return e->GetIntField(o, f);
 }
 
 jintArray nfc_jni_get_nfc_tag_type(JNIEnv *e, jobject o)
 {
-  jclass c;
-  jfieldID f;
-  jintArray techtypes;
-   
-  c = e->GetObjectClass(o);
-  f = e->GetFieldID(c, "mTechList","[I");
-
-  /* Read the techtypes  */
-  techtypes = (jintArray) e->GetObjectField(o, f);
-
-  return techtypes;
+   ScopedLocalRef<jclass> c(e, e->GetObjectClass(o));
+   jfieldID f = e->GetFieldID(c.get(), "mTechList","[I");
+   return (jintArray) e->GetObjectField(o, f);
 }
 
 
@@ -365,7 +317,7 @@
 const char* nfc_jni_get_status_name(NFCSTATUS status)
 {
    #define STATUS_ENTRY(status) { status, #status }
- 
+
    struct status_entry {
       NFCSTATUS   code;
       const char  *name;
@@ -414,7 +366,7 @@
    };
 
    int i = sizeof(sNameTable)/sizeof(status_entry);
- 
+
    while(i>0)
    {
       i--;
@@ -453,9 +405,10 @@
 /*
  *  Utility to get a technology tree and a corresponding handle list from a detected tag.
  */
-void nfc_jni_get_technology_tree(JNIEnv* e, phLibNfc_RemoteDevList_t* devList,
-        uint8_t count, jintArray* techList, jintArray* handleList,
-        jintArray* libnfcTypeList)
+void nfc_jni_get_technology_tree(JNIEnv* e, phLibNfc_RemoteDevList_t* devList, uint8_t count,
+                                 ScopedLocalRef<jintArray>* techList,
+                                 ScopedLocalRef<jintArray>* handleList,
+                                 ScopedLocalRef<jintArray>* libnfcTypeList)
 {
    int technologies[MAX_NUM_TECHNOLOGIES];
    int handles[MAX_NUM_TECHNOLOGIES];
@@ -546,18 +499,18 @@
 
    // Build the Java arrays
    if (techList != NULL) {
-       *techList = e->NewIntArray(index);
-       e->SetIntArrayRegion(*techList, 0, index, technologies);
+       techList->reset(e->NewIntArray(index));
+       e->SetIntArrayRegion(techList->get(), 0, index, technologies);
    }
 
    if (handleList != NULL) {
-       *handleList = e->NewIntArray(index);
-       e->SetIntArrayRegion(*handleList, 0, index, handles);
+       handleList->reset(e->NewIntArray(index));
+       e->SetIntArrayRegion(handleList->get(), 0, index, handles);
    }
 
    if (libnfcTypeList != NULL) {
-       *libnfcTypeList = e->NewIntArray(index);
-       e->SetIntArrayRegion(*libnfcTypeList, 0, index, libnfctypes);
+       libnfcTypeList->reset(e->NewIntArray(index));
+       e->SetIntArrayRegion(libnfcTypeList->get(), 0, index, libnfctypes);
    }
 }
 
diff --git a/nxp/jni/com_android_nfc.h b/nxp/jni/com_android_nfc.h
index b876dad..56c229f 100644
--- a/nxp/jni/com_android_nfc.h
+++ b/nxp/jni/com_android_nfc.h
@@ -17,10 +17,12 @@
 #ifndef __COM_ANDROID_NFC_JNI_H__
 #define __COM_ANDROID_NFC_JNI_H__
 
+#undef LOG_TAG
 #define LOG_TAG "NFCJNI"
 
 #include <JNIHelp.h>
 #include <jni.h>
+#include <ScopedLocalRef.h>
 
 #include <pthread.h>
 #include <sys/queue.h>
@@ -59,10 +61,10 @@
 #define PROPERTY_LLCP_WKS                 2
 #define PROPERTY_LLCP_OPT                 3
 #define PROPERTY_NFC_DISCOVERY_A          4
-#define PROPERTY_NFC_DISCOVERY_B          5  
+#define PROPERTY_NFC_DISCOVERY_B          5
 #define PROPERTY_NFC_DISCOVERY_F          6
 #define PROPERTY_NFC_DISCOVERY_15693      7
-#define PROPERTY_NFC_DISCOVERY_NCFIP      8                     
+#define PROPERTY_NFC_DISCOVERY_NCFIP      8
 
 /* Error codes */
 #define ERROR_BUFFER_TOO_SMALL            -12
@@ -140,10 +142,10 @@
    int discovery_modes_state[DISCOVERY_MODE_TABLE_SIZE];
    phLibNfc_sADD_Cfg_t discovery_cfg;
    phLibNfc_Registry_Info_t registry_info;
-   
+
    /* Secure Element selected */
    int seId;
-   
+
    /* LLCP params */
    int lto;
    int miu;
@@ -159,7 +161,7 @@
    /* p2p modes */
    int p2p_initiator_modes;
    int p2p_target_modes;
-   
+
 };
 
 typedef struct nfc_jni_native_monitor
@@ -231,9 +233,10 @@
 nfc_jni_native_monitor_t* nfc_jni_get_monitor(void);
 
 int get_technology_type(phNfc_eRemDevType_t type, uint8_t sak);
-void nfc_jni_get_technology_tree(JNIEnv* e, phLibNfc_RemoteDevList_t* devList,
-                        uint8_t count, jintArray* techList, jintArray* handleList,
-                        jintArray* typeList);
+void nfc_jni_get_technology_tree(JNIEnv* e, phLibNfc_RemoteDevList_t* devList, uint8_t count,
+                        ScopedLocalRef<jintArray>* techList,
+                        ScopedLocalRef<jintArray>* handleList,
+                        ScopedLocalRef<jintArray>* typeList);
 
 /* P2P */
 phLibNfc_Handle nfc_jni_get_p2p_device_handle(JNIEnv *e, jobject o);
diff --git a/nxp/jni/com_android_nfc_NativeLlcpServiceSocket.cpp b/nxp/jni/com_android_nfc_NativeLlcpServiceSocket.cpp
index 2fccfc9..406079c 100644
--- a/nxp/jni/com_android_nfc_NativeLlcpServiceSocket.cpp
+++ b/nxp/jni/com_android_nfc_NativeLlcpServiceSocket.cpp
@@ -16,6 +16,7 @@
 
 #include <semaphore.h>
 #include <errno.h>
+#include <ScopedLocalRef.h>
 
 #include "com_android_nfc.h"
 
@@ -73,7 +74,7 @@
    phLibNfc_Llcp_sSocketOptions_t sOptions;
    phNfc_sData_t sWorkingBuffer;
    jfieldID f;   
-   jclass clsNativeLlcpSocket;
+   ScopedLocalRef<jclass> clsNativeLlcpSocket(e, NULL);
    jobject clientSocket = NULL;
    struct nfc_jni_callback_data cb_data;
    phLibNfc_Handle hIncomingSocket, hServerSocket;
@@ -146,7 +147,7 @@
    }
 
    /* Get NativeConnectionOriented class object */
-   clsNativeLlcpSocket = e->GetObjectClass(clientSocket);
+   clsNativeLlcpSocket.reset(e->GetObjectClass(clientSocket));
    if(e->ExceptionCheck())
    {
       ALOGD("LLCP Socket get class object error");
@@ -154,15 +155,15 @@
    }
 
    /* Set socket handle */
-   f = e->GetFieldID(clsNativeLlcpSocket, "mHandle", "I");
+   f = e->GetFieldID(clsNativeLlcpSocket.get(), "mHandle", "I");
    e->SetIntField(clientSocket, f,(jint)hIncomingSocket);
 
    /* Set socket MIU */
-   f = e->GetFieldID(clsNativeLlcpSocket, "mLocalMiu", "I");
+   f = e->GetFieldID(clsNativeLlcpSocket.get(), "mLocalMiu", "I");
    e->SetIntField(clientSocket, f,(jint)miu);
 
    /* Set socket RW */
-   f = e->GetFieldID(clsNativeLlcpSocket, "mLocalRw", "I");
+   f = e->GetFieldID(clsNativeLlcpSocket.get(), "mLocalRw", "I");
    e->SetIntField(clientSocket, f,(jint)rw);
 
    TRACE("socket handle 0x%02x: MIU = %d, RW = %d\n",hIncomingSocket, miu, rw);
diff --git a/nxp/jni/com_android_nfc_NativeNfcManager.cpp b/nxp/jni/com_android_nfc_NativeNfcManager.cpp
index d82291b..d6b6aa5 100644
--- a/nxp/jni/com_android_nfc_NativeNfcManager.cpp
+++ b/nxp/jni/com_android_nfc_NativeNfcManager.cpp
@@ -24,6 +24,7 @@
 #include <hardware/hardware.h>
 #include <hardware/nfc.h>
 #include <cutils/properties.h>
+#include <ScopedLocalRef.h>
 
 #include "com_android_nfc.h"
 
@@ -86,7 +87,7 @@
 static void client_kill_deferred_call(void* arg)
 {
    struct nfc_jni_native_data *nat = (struct nfc_jni_native_data *)arg;
-   
+
    nat->running = FALSE;
 }
 
@@ -94,15 +95,15 @@
 {
    phDal4Nfc_Message_Wrapper_t  wrapper;
    phLibNfc_DeferredCall_t     *pMsg;
-   
+
    usleep(50000);
 
    ALOGD("Terminating client thread...");
-    
+
    pMsg = (phLibNfc_DeferredCall_t*)malloc(sizeof(phLibNfc_DeferredCall_t));
    pMsg->pCallback = client_kill_deferred_call;
    pMsg->pParameter = (void*)nat;
-   
+
    wrapper.msg.eMsgType = PH_LIBNFC_DEFERREDCALL_MSG;
    wrapper.msg.pMsgData = pMsg;
    wrapper.msg.Size     = sizeof(phLibNfc_DeferredCall_t);
@@ -359,7 +360,7 @@
       goto force_download;
    }
    TRACE("phLibNfc_Mgt_Initialize returned 0x%04x[%s]", status, nfc_jni_get_status_name(status));
-  
+
    /* Wait for callback response */
    if(sem_wait(&cb_data.sem))
    {
@@ -724,7 +725,7 @@
       }
    }
    TRACE("NFC client stopped");
-   
+
    nat->vm->DetachCurrentThread();
 
    return NULL;
@@ -738,7 +739,7 @@
 {
    3,
    { 0x46, 0x66, 0x6D }
-}; 
+};
 
 /*
  * Callbacks
@@ -762,7 +763,7 @@
    TRACE("Callback: nfc_jni_llcp_linkStatus_callback()");
 
    nat->vm->GetEnv( (void **)&e, nat->env_version);
-   
+
    /* Update link status */
    g_eLinkStatus = eLinkStatus;
 
@@ -805,7 +806,7 @@
       {
          ALOGE("Exception occured");
          kill_client(nat);
-      } 
+      }
    }
 }
 
@@ -906,37 +907,29 @@
    phLibNfc_RemoteDevList_t *psRemoteDevList,
    uint8_t uNofRemoteDev, NFCSTATUS status)
 {
-   JNIEnv *e;
    NFCSTATUS ret;
-   jclass tag_cls = NULL;
-   jobject target_array;
-   jobject tag;
-   jmethodID ctor;
-   jfieldID f;
    const char * typeName;
-   jbyteArray tagUid;
-   jbyteArray generalBytes = NULL;
-   struct nfc_jni_native_data *nat;
    struct timespec ts;
    phNfc_sData_t data;
    int i;
    int target_index = 0; // Target that will be reported (if multiple can be >0)
 
-   nat = (struct nfc_jni_native_data *)pContext;
-   
+   struct nfc_jni_native_data* nat = (struct nfc_jni_native_data *)pContext;
+
+   JNIEnv *e;
    nat->vm->GetEnv( (void **)&e, nat->env_version);
-   
+
    if(status == NFCSTATUS_DESELECTED)
    {
-      LOG_CALLBACK("nfc_jni_Discovery_notification_callback: Target deselected", status); 
-         
+      LOG_CALLBACK("nfc_jni_Discovery_notification_callback: Target deselected", status);
+
       /* Notify manager that a target was deselected */
       e->CallVoidMethod(nat->manager, cached_NfcManager_notifyTargetDeselected);
       if(e->ExceptionCheck())
       {
-         ALOGE("Exception occured");
+         ALOGE("Exception occurred");
          kill_client(nat);
-      } 
+      }
    }
    else
    {
@@ -945,6 +938,8 @@
 
       target_index = find_preferred_target(psRemoteDevList, uNofRemoteDev);
 
+      ScopedLocalRef<jobject> tag(e, NULL);
+
       /* Reset device connected flag */
       device_connected_flag = 1;
       phLibNfc_sRemoteDevInformation_t *remDevInfo = psRemoteDevList[target_index].psRemoteDevInfo;
@@ -952,61 +947,59 @@
       if((remDevInfo->RemDevType == phNfc_eNfcIP1_Initiator)
           || (remDevInfo->RemDevType == phNfc_eNfcIP1_Target))
       {
-
-         tag_cls = e->GetObjectClass(nat->cached_P2pDevice);
+         ScopedLocalRef<jclass> tag_cls(e, e->GetObjectClass(nat->cached_P2pDevice));
          if(e->ExceptionCheck())
          {
-            ALOGE("Get Object Class Error"); 
+            ALOGE("Get Object Class Error");
             kill_client(nat);
             return;
-         } 
-         
+         }
+
          /* New target instance */
-         ctor = e->GetMethodID(tag_cls, "<init>", "()V");
-         tag = e->NewObject(tag_cls, ctor);
-         
+         jmethodID ctor = e->GetMethodID(tag_cls.get(), "<init>", "()V");
+         tag.reset(e->NewObject(tag_cls.get(), ctor));
+
          /* Set P2P Target mode */
-         f = e->GetFieldID(tag_cls, "mMode", "I"); 
-         
+         jfieldID f = e->GetFieldID(tag_cls.get(), "mMode", "I");
+
          if(remDevInfo->RemDevType == phNfc_eNfcIP1_Initiator)
          {
             ALOGD("Discovered P2P Initiator");
-            e->SetIntField(tag, f, (jint)MODE_P2P_INITIATOR);
+            e->SetIntField(tag.get(), f, (jint)MODE_P2P_INITIATOR);
          }
          else
-         {    
+         {
             ALOGD("Discovered P2P Target");
-            e->SetIntField(tag, f, (jint)MODE_P2P_TARGET);
+            e->SetIntField(tag.get(), f, (jint)MODE_P2P_TARGET);
          }
-          
+
          if(remDevInfo->RemDevType == phNfc_eNfcIP1_Initiator)
          {
             /* Set General Bytes */
-            f = e->GetFieldID(tag_cls, "mGeneralBytes", "[B");
-   
+            f = e->GetFieldID(tag_cls.get(), "mGeneralBytes", "[B");
+
            TRACE("General Bytes length =");
            for(i=0;i<remDevInfo->RemoteDevInfo.NfcIP_Info.ATRInfo_Length;i++)
            {
                ALOGD("%02x ", remDevInfo->RemoteDevInfo.NfcIP_Info.ATRInfo[i]);
            }
 
-            generalBytes = e->NewByteArray(remDevInfo->RemoteDevInfo.NfcIP_Info.ATRInfo_Length);
-             
-            e->SetByteArrayRegion(generalBytes, 0, 
+            ScopedLocalRef<jbyteArray> generalBytes(e, e->NewByteArray(remDevInfo->RemoteDevInfo.NfcIP_Info.ATRInfo_Length));
+
+            e->SetByteArrayRegion(generalBytes.get(), 0,
                                   remDevInfo->RemoteDevInfo.NfcIP_Info.ATRInfo_Length,
                                   (jbyte *)remDevInfo->RemoteDevInfo.NfcIP_Info.ATRInfo);
-             
-            e->SetObjectField(tag, f, generalBytes);
+            e->SetObjectField(tag.get(), f, generalBytes.get());
          }
 
          /* Set tag handle */
-         f = e->GetFieldID(tag_cls, "mHandle", "I");
-         e->SetIntField(tag, f,(jint)remDevHandle);
+         f = e->GetFieldID(tag_cls.get(), "mHandle", "I");
+         e->SetIntField(tag.get(), f,(jint)remDevHandle);
          TRACE("Target handle = 0x%08x",remDevHandle);
       }
       else
       {
-        tag_cls = e->GetObjectClass(nat->cached_NfcTag);
+        ScopedLocalRef<jclass> tag_cls(e, e->GetObjectClass(nat->cached_NfcTag));
         if(e->ExceptionCheck())
         {
             kill_client(nat);
@@ -1014,8 +1007,8 @@
         }
 
         /* New tag instance */
-        ctor = e->GetMethodID(tag_cls, "<init>", "()V");
-        tag = e->NewObject(tag_cls, ctor);
+        jmethodID ctor = e->GetMethodID(tag_cls.get(), "<init>", "()V");
+        tag.reset(e->NewObject(tag_cls.get(), ctor));
 
         bool multi_protocol = false;
 
@@ -1026,74 +1019,73 @@
         }
 
         /* Set tag UID */
-        f = e->GetFieldID(tag_cls, "mUid", "[B");
+        jfieldID f = e->GetFieldID(tag_cls.get(), "mUid", "[B");
         data = get_target_uid(remDevInfo);
-        tagUid = e->NewByteArray(data.length);
+        ScopedLocalRef<jbyteArray> tagUid(e, e->NewByteArray(data.length));
         if(data.length > 0)
         {
-            e->SetByteArrayRegion(tagUid, 0, data.length, (jbyte *)data.buffer);
+           e->SetByteArrayRegion(tagUid.get(), 0, data.length, (jbyte *)data.buffer);
         }
-        e->SetObjectField(tag, f, tagUid);
+        e->SetObjectField(tag.get(), f, tagUid.get());
 
         /* Generate technology list */
-        jintArray techList;
-        jintArray handleList;
-        jintArray typeList;
+        ScopedLocalRef<jintArray> techList(e, NULL);
+        ScopedLocalRef<jintArray> handleList(e, NULL);
+        ScopedLocalRef<jintArray> typeList(e, NULL);
         nfc_jni_get_technology_tree(e, psRemoteDevList,
                 multi_protocol ? uNofRemoteDev : 1,
                 &techList, &handleList, &typeList);
 
         /* Push the technology list into the java object */
-        f = e->GetFieldID(tag_cls, "mTechList", "[I");
-        e->SetObjectField(tag, f, techList);
+        f = e->GetFieldID(tag_cls.get(), "mTechList", "[I");
+        e->SetObjectField(tag.get(), f, techList.get());
 
-        f = e->GetFieldID(tag_cls, "mTechHandles", "[I");
-        e->SetObjectField(tag, f, handleList);
+        f = e->GetFieldID(tag_cls.get(), "mTechHandles", "[I");
+        e->SetObjectField(tag.get(), f, handleList.get());
 
-        f = e->GetFieldID(tag_cls, "mTechLibNfcTypes", "[I");
-        e->SetObjectField(tag, f, typeList);
+        f = e->GetFieldID(tag_cls.get(), "mTechLibNfcTypes", "[I");
+        e->SetObjectField(tag.get(), f, typeList.get());
 
-        f = e->GetFieldID(tag_cls, "mConnectedTechIndex", "I");
-        e->SetIntField(tag, f,(jint)-1);
+        f = e->GetFieldID(tag_cls.get(), "mConnectedTechIndex", "I");
+        e->SetIntField(tag.get(), f,(jint)-1);
 
-        f = e->GetFieldID(tag_cls, "mConnectedHandle", "I");
-        e->SetIntField(tag, f,(jint)-1);
+        f = e->GetFieldID(tag_cls.get(), "mConnectedHandle", "I");
+        e->SetIntField(tag.get(), f,(jint)-1);
       }
 
       storedHandle = remDevHandle;
       if (nat->tag != NULL) {
           e->DeleteGlobalRef(nat->tag);
       }
-      nat->tag = e->NewGlobalRef(tag);
+      nat->tag = e->NewGlobalRef(tag.get());
 
-      /* Notify the service */   
+      /* Notify the service */
       TRACE("Notify Nfc Service");
       if((remDevInfo->RemDevType == phNfc_eNfcIP1_Initiator)
           || (remDevInfo->RemDevType == phNfc_eNfcIP1_Target))
       {
-         /* Store the hanlde of the P2P device */
+         /* Store the handle of the P2P device */
          hLlcpHandle = remDevHandle;
-         
+
          /* Notify manager that new a P2P device was found */
-         e->CallVoidMethod(nat->manager, cached_NfcManager_notifyLlcpLinkActivation, tag);
+         e->CallVoidMethod(nat->manager, cached_NfcManager_notifyLlcpLinkActivation, tag.get());
          if(e->ExceptionCheck())
          {
-            ALOGE("Exception occured");
+            ALOGE("Exception occurred");
             kill_client(nat);
-         }     
+         }
       }
       else
       {
          /* Notify manager that new a tag was found */
-         e->CallVoidMethod(nat->manager, cached_NfcManager_notifyNdefMessageListeners, tag);
+         e->CallVoidMethod(nat->manager, cached_NfcManager_notifyNdefMessageListeners, tag.get());
          if(e->ExceptionCheck())
          {
-            ALOGE("Exception occured");
+            ALOGE("Exception occurred");
             kill_client(nat);
-         }     
+         }
       }
-      e->DeleteLocalRef(tag);
-   } 
+   }
 }
 
 static void nfc_jni_init_callback(void *pContext, NFCSTATUS status)
@@ -1379,7 +1371,7 @@
    discovery_cfg.NfcIP_Mode = phNfc_eDefaultP2PMode;
    discovery_cfg.NfcIP_Target_Mode = 0;
    discovery_cfg.NfcIP_Tgt_Disable = TRUE;
- 
+
    /* Start Polling loop */
    TRACE("******  Stop NFC Discovery ******");
    REENTRANCE_LOCK();
@@ -1420,13 +1412,13 @@
 
     /* Retrieve native structure address */
     nat = nfc_jni_get_nat(e, o);
-   
+
     nfc_jni_stop_discovery_locked(nat);
 
     CONCURRENCY_UNLOCK();
 
 }
-    
+
 static void com_android_nfc_NfcManager_enableDiscovery(JNIEnv *e, jobject o) {
     NFCSTATUS ret;
     struct nfc_jni_native_data *nat;
@@ -1624,37 +1616,37 @@
    jobject obj;
    jfieldID f;
 
-   TRACE("******  Init Native Structure ******"); 
+   TRACE("******  Init Native Structure ******");
 
    /* Initialize native structure */
    nat = (nfc_jni_native_data*)malloc(sizeof(struct nfc_jni_native_data));
    if(nat == NULL)
    {
       ALOGD("malloc of nfc_jni_native_data failed");
-      return FALSE;   
+      return FALSE;
    }
    memset(nat, 0, sizeof(*nat));
    e->GetJavaVM(&(nat->vm));
    nat->env_version = e->GetVersion();
    nat->manager = e->NewGlobalRef(o);
-      
+
    cls = e->GetObjectClass(o);
    f = e->GetFieldID(cls, "mNative", "I");
    e->SetIntField(o, f, (jint)nat);
-                 
+
    /* Initialize native cached references */
    cached_NfcManager_notifyNdefMessageListeners = e->GetMethodID(cls,
       "notifyNdefMessageListeners","(Lcom/android/nfc/dhimpl/NativeNfcTag;)V");
 
    cached_NfcManager_notifyTransactionListeners = e->GetMethodID(cls,
       "notifyTransactionListeners", "([B)V");
-         
+
    cached_NfcManager_notifyLlcpLinkActivation = e->GetMethodID(cls,
       "notifyLlcpLinkActivation","(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");
-         
+
    cached_NfcManager_notifyLlcpLinkDeactivated = e->GetMethodID(cls,
       "notifyLlcpLinkDeactivated","(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");
-      
+
    cached_NfcManager_notifyTargetDeselected = e->GetMethodID(cls,
       "notifyTargetDeselected","()V");
 
@@ -1678,11 +1670,11 @@
       ALOGD("Native Structure initialization failed");
       return FALSE;
    }
-         
+
    if(nfc_jni_cache_object(e,"com/android/nfc/dhimpl/NativeP2pDevice",&(nat->cached_P2pDevice)) == -1)
    {
       ALOGD("Native Structure initialization failed");
-      return FALSE;   
+      return FALSE;
    }
    TRACE("****** Init Native Structure OK ******");
    return TRUE;
@@ -1698,7 +1690,7 @@
    char value[PROPERTY_VALUE_MAX];
 #endif
    jboolean result;
-   
+
    CONCURRENCY_LOCK();
 
 #ifdef TNFC_EMULATOR_ONLY
@@ -1830,12 +1822,11 @@
 /* Secure Element methods */
 static jintArray com_android_nfc_NfcManager_doGetSecureElementList(JNIEnv *e, jobject o) {
     NFCSTATUS ret;
-    jintArray list= NULL;
     phLibNfc_SE_List_t se_list[PHLIBNFC_MAXNO_OF_SE];
     uint8_t i, se_count = PHLIBNFC_MAXNO_OF_SE;
 
     TRACE("******  Get Secure Element List ******");
-    
+
     TRACE("phLibNfc_SE_GetSecureElementList()");
     REENTRANCE_LOCK();
     ret = phLibNfc_SE_GetSecureElementList(se_list, &se_count);
@@ -1843,13 +1834,13 @@
     if (ret != NFCSTATUS_SUCCESS) {
         ALOGE("phLibNfc_SE_GetSecureElementList() returned 0x%04x[%s]", ret,
                 nfc_jni_get_status_name(ret));
-        return list;
+        return NULL;
     }
     TRACE("phLibNfc_SE_GetSecureElementList() returned 0x%04x[%s]", ret,
             nfc_jni_get_status_name(ret));
 
     TRACE("Nb SE: %d", se_count);
-    list =e->NewIntArray(se_count);
+    jintArray result = e->NewIntArray(se_count);
     for (i = 0; i < se_count; i++) {
         if (se_list[i].eSE_Type == phLibNfc_SE_Type_SmartMX) {
             ALOGD("phLibNfc_SE_GetSecureElementList(): SMX detected");
@@ -1858,12 +1849,10 @@
             ALOGD("phLibNfc_SE_GetSecureElementList(): UICC detected");
             ALOGD("SE ID #%d: 0x%08x", i, se_list[i].hSecureElement);
         }
-        e->SetIntArrayRegion(list, i, 1, (jint*)&se_list[i].hSecureElement);
+        e->SetIntArrayRegion(result, i, 1, (jint*)&se_list[i].hSecureElement);
     }
 
-    e->DeleteLocalRef(list);
-
-    return list;
+    return result;
 }
 
 static void com_android_nfc_NfcManager_doSelectSecureElement(JNIEnv *e, jobject o) {
@@ -1929,7 +1918,7 @@
     ret = phLibNfc_SE_SetMode(nat->seId, phLibNfc_SE_ActModeDefault,
            nfc_jni_se_set_mode_callback, (void *)&cb_data);
     REENTRANCE_UNLOCK();
-       
+
     TRACE("phLibNfc_SE_SetMode returned 0x%02x", ret);
     if (ret != NFCSTATUS_PENDING) {
         ALOGE("phLibNfc_SE_SetMode() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
@@ -2031,7 +2020,7 @@
    else
    {
       ALOGE("phLibNfc_Llcp_Activate() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
-      return JNI_FALSE;   
+      return JNI_FALSE;
    }
 }
 
@@ -2049,10 +2038,10 @@
    phLibNfc_Llcp_sLinkParameters_t sParams;
    jclass clsNativeConnectionlessSocket;
    jfieldID f;
-   
+
    /* Retrieve native structure address */
-   nat = nfc_jni_get_nat(e, o); 
-   
+   nat = nfc_jni_get_nat(e, o);
+
    /* Allocate Working buffer length */
    phLibNfc_Llcp_GetLocalInfo(hLlcpHandle, &sParams);
    sWorkingBuffer.length = sParams.miu + 1; // extra byte for SAP
@@ -2068,7 +2057,7 @@
                               nfc_jni_llcp_transport_socket_err_callback,
                               (void*)nat);
    REENTRANCE_UNLOCK();
- 
+
    if(ret != NFCSTATUS_SUCCESS)
    {
       lastErrorStatus = ret;
@@ -2085,7 +2074,7 @@
        serviceName.buffer = (uint8_t*)e->GetStringUTFChars(sn, NULL);
        serviceName.length = (uint32_t)e->GetStringUTFLength(sn);
    }
-   
+
    /* Bind socket */
    TRACE("phLibNfc_Llcp_Bind(hSocket=0x%08x, nSap=0x%02x)", hLlcpSocket, nSap);
    REENTRANCE_LOCK();
@@ -2097,41 +2086,41 @@
       ALOGE("phLibNfc_Llcp_Bind() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
       /* Close socket created */
       REENTRANCE_LOCK();
-      ret = phLibNfc_Llcp_Close(hLlcpSocket); 
+      ret = phLibNfc_Llcp_Close(hLlcpSocket);
       REENTRANCE_UNLOCK();
       goto error;
    }
    TRACE("phLibNfc_Llcp_Bind() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
- 
-   
+
+
    /* Create new NativeLlcpConnectionlessSocket object */
    if(nfc_jni_cache_object(e,"com/android/nfc/dhimpl/NativeLlcpConnectionlessSocket",&(connectionlessSocket)) == -1)
    {
       goto error;
-   } 
-   
+   }
+
    /* Get NativeConnectionless class object */
    clsNativeConnectionlessSocket = e->GetObjectClass(connectionlessSocket);
    if(e->ExceptionCheck())
    {
       goto error;
    }
-   
+
    /* Set socket handle */
    f = e->GetFieldID(clsNativeConnectionlessSocket, "mHandle", "I");
    e->SetIntField(connectionlessSocket, f,(jint)hLlcpSocket);
-   TRACE("Connectionless socket Handle = %02x\n",hLlcpSocket);  
-   
+   TRACE("Connectionless socket Handle = %02x\n",hLlcpSocket);
+
    /* Set the miu link of the connectionless socket */
    f = e->GetFieldID(clsNativeConnectionlessSocket, "mLinkMiu", "I");
    e->SetIntField(connectionlessSocket, f,(jint)PHFRINFC_LLCP_MIU_DEFAULT);
-   TRACE("Connectionless socket Link MIU = %d\n",PHFRINFC_LLCP_MIU_DEFAULT);  
-   
+   TRACE("Connectionless socket Link MIU = %d\n",PHFRINFC_LLCP_MIU_DEFAULT);
+
    /* Set socket SAP */
    f = e->GetFieldID(clsNativeConnectionlessSocket, "mSap", "I");
    e->SetIntField(connectionlessSocket, f,(jint)nSap);
-   TRACE("Connectionless socket SAP = %d\n",nSap);  
-   
+   TRACE("Connectionless socket SAP = %d\n",nSap);
+
    return connectionlessSocket;
 error:
    if (serviceName.buffer != NULL) {
@@ -2155,20 +2144,20 @@
    struct nfc_jni_native_data *nat;
    jobject serviceSocket = NULL;
    jclass clsNativeLlcpServiceSocket;
-   jfieldID f;  
-  
+   jfieldID f;
+
    /* Retrieve native structure address */
-   nat = nfc_jni_get_nat(e, o); 
-   
+   nat = nfc_jni_get_nat(e, o);
+
    /* Set Connection Oriented socket options */
    sOptions.miu = miu;
-   sOptions.rw  = rw;  
-  
+   sOptions.rw  = rw;
+
    /* Allocate Working buffer length */
    sWorkingBuffer.length = (miu*rw)+ miu + linearBufferLength;
    sWorkingBuffer.buffer = (uint8_t*)malloc(sWorkingBuffer.length);
 
-   
+
    /* Create socket */
    TRACE("phLibNfc_Llcp_Socket(hRemoteDevice=0x%08x, eType=phFriNfc_LlcpTransport_eConnectionOriented, ...)", hLlcpHandle);
    REENTRANCE_LOCK();
@@ -2179,7 +2168,7 @@
                               nfc_jni_llcp_transport_socket_err_callback,
                               (void*)nat);
    REENTRANCE_UNLOCK();
-                                                     
+
    if(ret != NFCSTATUS_SUCCESS)
    {
       ALOGE("phLibNfc_Llcp_Socket() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
@@ -2207,7 +2196,7 @@
       lastErrorStatus = ret;
       ALOGE("phLibNfc_Llcp_Bind() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
       /* Close socket created */
-      ret = phLibNfc_Llcp_Close(hLlcpSocket); 
+      ret = phLibNfc_Llcp_Close(hLlcpSocket);
       goto error;
    }
    TRACE("phLibNfc_Llcp_Bind() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
@@ -2218,53 +2207,53 @@
                                nfc_jni_llcp_transport_listen_socket_callback,
                                (void*)hLlcpSocket);
    REENTRANCE_UNLOCK();
-                               
+
    if(ret != NFCSTATUS_SUCCESS)
    {
       ALOGE("phLibNfc_Llcp_Listen() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
       lastErrorStatus = ret;
       /* Close created socket */
       REENTRANCE_LOCK();
-      ret = phLibNfc_Llcp_Close(hLlcpSocket); 
+      ret = phLibNfc_Llcp_Close(hLlcpSocket);
       REENTRANCE_UNLOCK();
       goto error;
-   }                         
+   }
    TRACE("phLibNfc_Llcp_Listen() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
-   
+
    /* Create new NativeLlcpServiceSocket object */
    if(nfc_jni_cache_object(e,"com/android/nfc/dhimpl/NativeLlcpServiceSocket",&(serviceSocket)) == -1)
    {
       ALOGE("Llcp Socket object creation error");
       goto error;
-   } 
-   
+   }
+
    /* Get NativeLlcpServiceSocket class object */
    clsNativeLlcpServiceSocket = e->GetObjectClass(serviceSocket);
    if(e->ExceptionCheck())
    {
       ALOGE("Llcp Socket get object class error");
       goto error;
-   } 
-   
+   }
+
    /* Set socket handle */
    f = e->GetFieldID(clsNativeLlcpServiceSocket, "mHandle", "I");
    e->SetIntField(serviceSocket, f,(jint)hLlcpSocket);
-   TRACE("Service socket Handle = %02x\n",hLlcpSocket);  
-   
+   TRACE("Service socket Handle = %02x\n",hLlcpSocket);
+
    /* Set socket linear buffer length */
    f = e->GetFieldID(clsNativeLlcpServiceSocket, "mLocalLinearBufferLength", "I");
    e->SetIntField(serviceSocket, f,(jint)linearBufferLength);
-   TRACE("Service socket Linear buffer length = %02x\n",linearBufferLength);  
-   
+   TRACE("Service socket Linear buffer length = %02x\n",linearBufferLength);
+
    /* Set socket MIU */
    f = e->GetFieldID(clsNativeLlcpServiceSocket, "mLocalMiu", "I");
    e->SetIntField(serviceSocket, f,(jint)miu);
-   TRACE("Service socket MIU = %d\n",miu);  
-   
+   TRACE("Service socket MIU = %d\n",miu);
+
    /* Set socket RW */
    f = e->GetFieldID(clsNativeLlcpServiceSocket, "mLocalRw", "I");
    e->SetIntField(serviceSocket, f,(jint)rw);
-   TRACE("Service socket RW = %d\n",rw);   
+   TRACE("Service socket RW = %d\n",rw);
 
    return serviceSocket;
 error:
@@ -2284,14 +2273,14 @@
    struct nfc_jni_native_data *nat;
    jclass clsNativeLlcpSocket;
    jfieldID f;
-   
+
    /* Retrieve native structure address */
-   nat = nfc_jni_get_nat(e, o); 
-   
+   nat = nfc_jni_get_nat(e, o);
+
    /* Set Connection Oriented socket options */
    sOptions.miu = miu;
    sOptions.rw  = rw;
-   
+
    /* Allocate Working buffer length */
    sWorkingBuffer.length = (miu*rw)+ miu + linearBufferLength;
    sWorkingBuffer.buffer = (uint8_t*)malloc(sWorkingBuffer.length);
@@ -2314,22 +2303,22 @@
       return NULL;
    }
    TRACE("phLibNfc_Llcp_Socket() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
-   
+
    /* Create new NativeLlcpSocket object */
    if(nfc_jni_cache_object(e,"com/android/nfc/dhimpl/NativeLlcpSocket",&(clientSocket)) == -1)
    {
-      ALOGE("Llcp socket object creation error");  
-      return NULL;           
-   } 
-   
+      ALOGE("Llcp socket object creation error");
+      return NULL;
+   }
+
    /* Get NativeConnectionless class object */
    clsNativeLlcpSocket = e->GetObjectClass(clientSocket);
    if(e->ExceptionCheck())
    {
-      ALOGE("Get class object error");    
-      return NULL;  
+      ALOGE("Get class object error");
+      return NULL;
    }
-   
+
    /* Test if an SAP number is present */
    if(nSap != 0)
    {
@@ -2344,41 +2333,41 @@
          ALOGE("phLibNfc_Llcp_Bind() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
          /* Close socket created */
          REENTRANCE_LOCK();
-         ret = phLibNfc_Llcp_Close(hLlcpSocket); 
+         ret = phLibNfc_Llcp_Close(hLlcpSocket);
          REENTRANCE_UNLOCK();
          return NULL;
       }
       TRACE("phLibNfc_Llcp_Bind() returned 0x%04x[%s]", ret, nfc_jni_get_status_name(ret));
-      
+
       /* Set socket SAP */
       f = e->GetFieldID(clsNativeLlcpSocket, "mSap", "I");
       e->SetIntField(clientSocket, f,(jint)nSap);
-      TRACE("socket SAP = %d\n",nSap);    
-   }  
-      
+      TRACE("socket SAP = %d\n",nSap);
+   }
+
    /* Set socket handle */
    f = e->GetFieldID(clsNativeLlcpSocket, "mHandle", "I");
    e->SetIntField(clientSocket, f,(jint)hLlcpSocket);
-   TRACE("socket Handle = %02x\n",hLlcpSocket);  
-   
+   TRACE("socket Handle = %02x\n",hLlcpSocket);
+
    /* Set socket MIU */
    f = e->GetFieldID(clsNativeLlcpSocket, "mLocalMiu", "I");
    e->SetIntField(clientSocket, f,(jint)miu);
-   TRACE("socket MIU = %d\n",miu);  
-   
+   TRACE("socket MIU = %d\n",miu);
+
    /* Set socket RW */
    f = e->GetFieldID(clsNativeLlcpSocket, "mLocalRw", "I");
    e->SetIntField(clientSocket, f,(jint)rw);
-   TRACE("socket RW = %d\n",rw);   
-   
-  
+   TRACE("socket RW = %d\n",rw);
+
+
    return clientSocket;
 }
 
 static jint com_android_nfc_NfcManager_doGetLastError(JNIEnv *e, jobject o)
 {
    TRACE("Last Error Status = 0x%02x",lastErrorStatus);
-   
+
    if(lastErrorStatus == NFCSTATUS_BUFFER_TOO_SMALL)
    {
       return ERROR_BUFFER_TOO_SMALL;
@@ -2544,37 +2533,37 @@
 
    {"doInitialize", "()Z",
       (void *)com_android_nfc_NfcManager_initialize},
- 
+
    {"doDeinitialize", "()Z",
       (void *)com_android_nfc_NfcManager_deinitialize},
-      
+
    {"enableDiscovery", "()V",
       (void *)com_android_nfc_NfcManager_enableDiscovery},
 
    {"doGetSecureElementList", "()[I",
       (void *)com_android_nfc_NfcManager_doGetSecureElementList},
-      
+
    {"doSelectSecureElement", "()V",
       (void *)com_android_nfc_NfcManager_doSelectSecureElement},
-      
+
    {"doDeselectSecureElement", "()V",
       (void *)com_android_nfc_NfcManager_doDeselectSecureElement},
-      
+
    {"doCheckLlcp", "()Z",
       (void *)com_android_nfc_NfcManager_doCheckLlcp},
-      
+
    {"doActivateLlcp", "()Z",
       (void *)com_android_nfc_NfcManager_doActivateLlcp},
-            
+
    {"doCreateLlcpConnectionlessSocket", "(ILjava/lang/String;)Lcom/android/nfc/dhimpl/NativeLlcpConnectionlessSocket;",
       (void *)com_android_nfc_NfcManager_doCreateLlcpConnectionlessSocket},
-        
+
    {"doCreateLlcpServiceSocket", "(ILjava/lang/String;III)Lcom/android/nfc/dhimpl/NativeLlcpServiceSocket;",
       (void *)com_android_nfc_NfcManager_doCreateLlcpServiceSocket},
-      
+
    {"doCreateLlcpSocket", "(IIII)Lcom/android/nfc/dhimpl/NativeLlcpSocket;",
       (void *)com_android_nfc_NfcManager_doCreateLlcpSocket},
-      
+
    {"doGetLastError", "()I",
       (void *)com_android_nfc_NfcManager_doGetLastError},
 
@@ -2601,9 +2590,9 @@
 
    {"doDump", "()Ljava/lang/String;",
       (void *)com_android_nfc_NfcManager_doDump},
-};   
-  
-      
+};
+
+
 int register_com_android_nfc_NativeNfcManager(JNIEnv *e)
 {
     nfc_jni_native_monitor_t *nfc_jni_native_monitor;
diff --git a/nxp/jni/com_android_nfc_NativeNfcSecureElement.cpp b/nxp/jni/com_android_nfc_NativeNfcSecureElement.cpp
index bb1bb2a..79887a0 100755
--- a/nxp/jni/com_android_nfc_NativeNfcSecureElement.cpp
+++ b/nxp/jni/com_android_nfc_NativeNfcSecureElement.cpp
@@ -152,12 +152,12 @@
       TRACE("Secure Element Handle: 0x%08x", secureElementHandle);
 
       /* Set type name */      
-      jintArray techList;
+      ScopedLocalRef<jintArray> techList(e, NULL);
       nfc_jni_get_technology_tree(e, psRemoteDevList,uNofRemoteDev, &techList, NULL, NULL);
 
       // TODO: Should use the "connected" technology, for now use the first
-      if ((techList != NULL) && e->GetArrayLength(techList) > 0) {
-         e->GetIntArrayRegion(techList, 0, 1, &SecureElementTech);
+      if ((techList.get() != NULL) && e->GetArrayLength(techList.get()) > 0) {
+         e->GetIntArrayRegion(techList.get(), 0, 1, &SecureElementTech);
          TRACE("Store Secure Element Info\n");
          SecureElementInfo = psRemoteDevList->psRemoteDevInfo;
 
@@ -167,10 +167,6 @@
          ALOGE("Discovered secure element, but could not resolve tech");
          status = NFCSTATUS_FAILED;
       }
-
-      // This thread may not return to the virtual machine for a long time
-      // so make sure to delete the local refernce to the tech list.
-      e->DeleteLocalRef(techList);
    }
 
 clean_and_return:
@@ -730,16 +726,12 @@
    jintArray techList;
    TRACE("Get Secure element Type function ");
       
-   if(handle == secureElementHandle)
-   {
-      techList = e->NewIntArray(1);
-      e->SetIntArrayRegion(techList, 0, 1, &SecureElementTech);
-      return techList;
-   }
-   else
-   {
+   if (handle != secureElementHandle) {
       return NULL;
    }
+   jintArray result = e->NewIntArray(1);
+   e->SetIntArrayRegion(result, 0, 1, &SecureElementTech);
+   return result;
 }
 
 
diff --git a/nxp/jni/com_android_nfc_NativeNfcTag.cpp b/nxp/jni/com_android_nfc_NativeNfcTag.cpp
index a621d2a..1f469e4 100644
--- a/nxp/jni/com_android_nfc_NativeNfcTag.cpp
+++ b/nxp/jni/com_android_nfc_NativeNfcTag.cpp
@@ -16,6 +16,8 @@
 
 #include <semaphore.h>
 #include <errno.h>
+#include <ScopedLocalRef.h>
+#include <ScopedPrimitiveArray.h>
 
 #include "com_android_nfc.h"
 #include "phNfcHalTypes.h"
@@ -133,7 +135,7 @@
 {
    struct nfc_jni_callback_data * pCallbackData = (struct nfc_jni_callback_data *) pContext;
    LOG_CALLBACK("nfc_jni_transceive_callback", status);
-  
+
    nfc_jni_transceive_buffer = pResBuffer;
 
    /* Report the callback status and wake up the caller */
@@ -196,8 +198,8 @@
    TRACE("phLibNfc_Ndef_Read()");
    REENTRANCE_LOCK();
    status = phLibNfc_Ndef_Read(handle, &nfc_jni_ndef_rw,
-                               phLibNfc_Ndef_EBegin, 
-                               nfc_jni_tag_rw_callback, 
+                               phLibNfc_Ndef_EBegin,
+                               nfc_jni_tag_rw_callback,
                                (void *)&cb_data);
    REENTRANCE_UNLOCK();
    if(status != NFCSTATUS_PENDING)
@@ -206,7 +208,7 @@
       goto clean_and_return;
    }
    TRACE("phLibNfc_Ndef_Read() returned 0x%04x[%s]", status, nfc_jni_get_status_name(status));
-    
+
    /* Wait for callback response */
    if(sem_wait(&cb_data.sem))
    {
@@ -229,7 +231,7 @@
 
    return buf;
 }
- 
+
 
 static jboolean com_android_nfc_NativeNfcTag_doWrite(JNIEnv *e,
    jobject o, jbyteArray buf)
@@ -292,26 +294,25 @@
 static void set_target_pollBytes(JNIEnv *e, jobject tag,
         phLibNfc_sRemoteDevInformation_t *psRemoteDevInfo)
 {
-    jclass tag_cls = e->GetObjectClass(tag);
-    jfieldID f = e->GetFieldID(tag_cls, "mTechPollBytes", "[[B");
+    ScopedLocalRef<jclass> tag_cls(e, e->GetObjectClass(tag));
+    jfieldID f = e->GetFieldID(tag_cls.get(), "mTechPollBytes", "[[B");
 
-    jobjectArray existingPollBytes = (jobjectArray) e->GetObjectField(tag, f);
-
-    if (existingPollBytes != NULL) {
+    ScopedLocalRef<jobjectArray> existingPollBytes(e, (jobjectArray) e->GetObjectField(tag, f));
+    if (existingPollBytes.get() != NULL) {
         return;
     }
 
-    jfieldID techListField = e->GetFieldID(tag_cls, "mTechList", "[I");
-    jintArray techList = (jintArray) e->GetObjectField(tag, techListField);
-    jint *techId = e->GetIntArrayElements(techList, 0);
-    int techListLength = e->GetArrayLength(techList);
+    jfieldID techListField = e->GetFieldID(tag_cls.get(), "mTechList", "[I");
+    ScopedLocalRef<jintArray> techList(e, (jintArray) e->GetObjectField(tag, techListField));
+    ScopedIntArrayRO techIds(e, techList.get());
+    int techListLength = techIds.size();
 
-    jbyteArray pollBytes = e->NewByteArray(0);
-    jobjectArray techPollBytes = e->NewObjectArray(techListLength,
-            e->GetObjectClass(pollBytes), 0);
+    ScopedLocalRef<jbyteArray> pollBytes(e, e->NewByteArray(0));
+    ScopedLocalRef<jclass> byteArrayClass(e, e->GetObjectClass(pollBytes.get()));
+    ScopedLocalRef<jobjectArray> techPollBytes(e, e->NewObjectArray(techListLength, byteArrayClass.get(), NULL));
 
     for (int tech = 0; tech < techListLength; tech++) {
-        switch(techId[tech])
+        switch(techIds[tech])
         {
             /* ISO14443-3A: ATQA/SENS_RES */
             case TARGET_TYPE_ISO14443_3A:
@@ -320,56 +321,52 @@
                     // at {0x00, 0x0C} in the spec. So eJewel can safely be
                     // translated to {0x00, 0x0C}.
                     const static jbyte JewelAtqA[2] = {0x00, 0x0C};
-                    pollBytes = e->NewByteArray(2);
-                    e->SetByteArrayRegion(pollBytes, 0, 2, (jbyte*) JewelAtqA);
-                }
-                else {
-                    pollBytes = e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AtqA));
-                    e->SetByteArrayRegion(pollBytes, 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AtqA),
+                    pollBytes.reset(e->NewByteArray(2));
+                    e->SetByteArrayRegion(pollBytes.get(), 0, 2, (jbyte*) JewelAtqA);
+                } else {
+                    pollBytes.reset(e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AtqA)));
+                    e->SetByteArrayRegion(pollBytes.get(), 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AtqA),
                                           (jbyte *)psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AtqA);
                 }
                 break;
             /* ISO14443-3B: Application data (4 bytes) and Protocol Info (3 bytes) from ATQB/SENSB_RES */
             case TARGET_TYPE_ISO14443_3B:
-                pollBytes = e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.AppData)
-                                           + sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.ProtInfo));
-                e->SetByteArrayRegion(pollBytes, 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.AppData),
+                pollBytes.reset(e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.AppData)
+                        + sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.ProtInfo)));
+                e->SetByteArrayRegion(pollBytes.get(), 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.AppData),
                                       (jbyte *)psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.AppData);
-                e->SetByteArrayRegion(pollBytes, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.AppData),
+                e->SetByteArrayRegion(pollBytes.get(), sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.AppData),
                                       sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.ProtInfo),
                                       (jbyte *)psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.AtqB.AtqResInfo.ProtInfo);
                 break;
             /* JIS_X_6319_4: PAD0 (2 byte), PAD1 (2 byte), MRTI(2 byte), PAD2 (1 byte), RC (2 byte) */
             case TARGET_TYPE_FELICA:
-                pollBytes = e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.PMm)
-                                           + sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.SystemCode));
-                e->SetByteArrayRegion(pollBytes, 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.PMm),
+                pollBytes.reset(e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.PMm)
+                        + sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.SystemCode)));
+                e->SetByteArrayRegion(pollBytes.get(), 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.PMm),
                                       (jbyte *)psRemoteDevInfo->RemoteDevInfo.Felica_Info.PMm);
-                e->SetByteArrayRegion(pollBytes, sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.PMm),
+                e->SetByteArrayRegion(pollBytes.get(), sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.PMm),
                                       sizeof(psRemoteDevInfo->RemoteDevInfo.Felica_Info.SystemCode),
                                       (jbyte *)psRemoteDevInfo->RemoteDevInfo.Felica_Info.SystemCode);
                 break;
             /* ISO15693: response flags (1 byte), DSFID (1 byte) */
             case TARGET_TYPE_ISO15693:
-                pollBytes = e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags)
-                                           + sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Dsfid));
-                e->SetByteArrayRegion(pollBytes, 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags),
+                pollBytes.reset(e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags)
+                        + sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Dsfid)));
+                e->SetByteArrayRegion(pollBytes.get(), 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags),
                                       (jbyte *)&psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags);
-                e->SetByteArrayRegion(pollBytes, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags),
+                e->SetByteArrayRegion(pollBytes.get(), sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags),
                                       sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Dsfid),
                                       (jbyte *)&psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Dsfid);
                 break;
             default:
-                pollBytes = e->NewByteArray(0);
+                pollBytes.reset(e->NewByteArray(0));
                 break;
         }
-        e->SetObjectArrayElement(techPollBytes, tech, pollBytes);
+        e->SetObjectArrayElement(techPollBytes.get(), tech, pollBytes.get());
     }
 
-    e->SetObjectField(tag, f, techPollBytes);
-
-    e->ReleaseIntArrayElements(techList, techId, 0);
-
+    e->SetObjectField(tag, f, techPollBytes.get());
 }
 
 /*
@@ -378,31 +375,30 @@
 static void set_target_activationBytes(JNIEnv *e, jobject tag,
         phLibNfc_sRemoteDevInformation_t *psRemoteDevInfo)
 {
-    jclass tag_cls = e->GetObjectClass(tag);
+    ScopedLocalRef<jclass> tag_cls(e, e->GetObjectClass(tag));
 
-    jfieldID f = e->GetFieldID(tag_cls, "mTechActBytes", "[[B");
-    jobjectArray existingActBytes = (jobjectArray) e->GetObjectField(tag, f);
-
-    if (existingActBytes != NULL) {
+    jfieldID f = e->GetFieldID(tag_cls.get(), "mTechActBytes", "[[B");
+    ScopedLocalRef<jobjectArray> existingActBytes(e, (jobjectArray) e->GetObjectField(tag, f));
+    if (existingActBytes.get() != NULL) {
         return;
     }
 
-    jfieldID techListField = e->GetFieldID(tag_cls, "mTechList", "[I");
-    jintArray techList = (jintArray) e->GetObjectField(tag, techListField);
-    int techListLength = e->GetArrayLength(techList);
-    jint *techId = e->GetIntArrayElements(techList, 0);
+    jfieldID techListField = e->GetFieldID(tag_cls.get(), "mTechList", "[I");
+    ScopedLocalRef<jintArray> techList(e, (jintArray) e->GetObjectField(tag, techListField));
+    ScopedIntArrayRO techIds(e, techList.get());
+    int techListLength = techIds.size();
 
-    jbyteArray actBytes = e->NewByteArray(0);
-    jobjectArray techActBytes = e->NewObjectArray(techListLength,
-            e->GetObjectClass(actBytes), 0);
+    ScopedLocalRef<jbyteArray> actBytes(e, e->NewByteArray(0));
+    ScopedLocalRef<jclass> byteArrayClass(e, e->GetObjectClass(actBytes.get()));
+    ScopedLocalRef<jobjectArray> techActBytes(e, e->NewObjectArray(techListLength, byteArrayClass.get(), 0));
 
     for (int tech = 0; tech < techListLength; tech++) {
-        switch(techId[tech]) {
+        switch(techIds[tech]) {
 
             /* ISO14443-3A: SAK/SEL_RES */
             case TARGET_TYPE_ISO14443_3A:
-                actBytes = e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.Sak));
-                e->SetByteArrayRegion(actBytes, 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.Sak),
+                actBytes.reset(e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.Sak)));
+                e->SetByteArrayRegion(actBytes.get(), 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.Sak),
                                       (jbyte *)&psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.Sak);
                 break;
             /* ISO14443-3A & ISO14443-4: SAK/SEL_RES, historical bytes from ATS */
@@ -410,45 +406,40 @@
             case TARGET_TYPE_ISO14443_4:
                 // Determine whether -A or -B
                 if (psRemoteDevInfo->RemDevType == phNfc_eISO14443_B_PICC ||
-                    psRemoteDevInfo->RemDevType == phNfc_eISO14443_4B_PICC) {
-                    actBytes = e->NewByteArray(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.HiLayerRespLength);
-                    e->SetByteArrayRegion(actBytes, 0, psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.HiLayerRespLength,
+                        psRemoteDevInfo->RemDevType == phNfc_eISO14443_4B_PICC) {
+                    actBytes.reset(e->NewByteArray(psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.HiLayerRespLength));
+                    e->SetByteArrayRegion(actBytes.get(), 0, psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.HiLayerRespLength,
                                       (jbyte *)psRemoteDevInfo->RemoteDevInfo.Iso14443B_Info.HiLayerResp);
-                }
-                else if (psRemoteDevInfo->RemDevType == phNfc_eISO14443_A_PICC ||
-                         psRemoteDevInfo->RemDevType == phNfc_eISO14443_4A_PICC) {
-                    actBytes = e->NewByteArray(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AppDataLength);
-                    e->SetByteArrayRegion(actBytes, 0,
+                } else if (psRemoteDevInfo->RemDevType == phNfc_eISO14443_A_PICC ||
+                        psRemoteDevInfo->RemDevType == phNfc_eISO14443_4A_PICC) {
+                    actBytes.reset(e->NewByteArray(psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AppDataLength));
+                    e->SetByteArrayRegion(actBytes.get(), 0,
                                           psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AppDataLength,
                                           (jbyte *)psRemoteDevInfo->RemoteDevInfo.Iso14443A_Info.AppData);
                 }
                 break;
             /* ISO15693: response flags (1 byte), DSFID (1 byte) */
             case TARGET_TYPE_ISO15693:
-                actBytes = e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags)
-                                           + sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Dsfid));
-                e->SetByteArrayRegion(actBytes, 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags),
+                actBytes.reset(e->NewByteArray(sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags)
+                        + sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Dsfid)));
+                e->SetByteArrayRegion(actBytes.get(), 0, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags),
                                       (jbyte *)&psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags);
-                e->SetByteArrayRegion(actBytes, sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags),
+                e->SetByteArrayRegion(actBytes.get(), sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Flags),
                                       sizeof(psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Dsfid),
                                       (jbyte *)&psRemoteDevInfo->RemoteDevInfo.Iso15693_Info.Dsfid);
                 break;
             default:
-                actBytes = e->NewByteArray(0);
+                actBytes.reset(e->NewByteArray(0));
                 break;
         }
-        e->SetObjectArrayElement(techActBytes, tech, actBytes);
+        e->SetObjectArrayElement(techActBytes.get(), tech, actBytes.get());
     }
-    e->SetObjectField(tag, f, techActBytes);
-
-    e->ReleaseIntArrayElements(techList, techId, 0);
+    e->SetObjectField(tag, f, techActBytes.get());
 }
 
 static jint com_android_nfc_NativeNfcTag_doConnect(JNIEnv *e,
    jobject o, phLibNfc_Handle handle)
 {
-   jclass cls;
-   jfieldID f;
    jint status;
    struct nfc_jni_callback_data cb_data;
    phLibNfc_sRemoteDevInformation_t* pRemDevInfo = NULL;
@@ -504,8 +495,6 @@
 static jint com_android_nfc_NativeNfcTag_doHandleReconnect(JNIEnv *e,
    jobject o, phLibNfc_Handle handle)
 {
-   jclass cls;
-   jfieldID f;
    jint status;
    struct nfc_jni_callback_data cb_data;
    phLibNfc_sRemoteDevInformation_t* pRemDevInfo = NULL;
@@ -578,8 +567,6 @@
 static jboolean com_android_nfc_NativeNfcTag_doDisconnect(JNIEnv *e, jobject o)
 {
    phLibNfc_Handle handle = 0;
-   jclass cls;
-   jfieldID f;
    NFCSTATUS status;
    jboolean result = JNI_FALSE;
    struct nfc_jni_callback_data cb_data;
@@ -601,7 +588,7 @@
 
    /* Disconnect */
    TRACE("Disconnecting from tag (%x)", handle);
-   
+
    if (handle == -1) {
        // Was never connected to any tag, exit
        result = JNI_TRUE;
@@ -636,7 +623,7 @@
        ALOGE("Failed to wait for semaphore (errno=0x%08x)", errno);
        goto clean_and_return;
     }
-   
+
     /* Disconnect Status */
     if(cb_data.status != NFCSTATUS_SUCCESS)
     {
diff --git a/nxp/jni/com_android_nfc_NativeP2pDevice.cpp b/nxp/jni/com_android_nfc_NativeP2pDevice.cpp
index fa46052..19f3ecc 100644
--- a/nxp/jni/com_android_nfc_NativeP2pDevice.cpp
+++ b/nxp/jni/com_android_nfc_NativeP2pDevice.cpp
@@ -17,6 +17,7 @@
 
 #include <semaphore.h>
 #include <errno.h>
+#include <ScopedLocalRef.h>
 
 #include "com_android_nfc.h"
 
@@ -122,7 +123,7 @@
     jboolean result = JNI_FALSE;
     struct nfc_jni_callback_data cb_data;
 
-    jclass target_cls = NULL;
+    ScopedLocalRef<jclass> target_cls(e, NULL);
     jobject tag;
     jmethodID ctor;
     jfieldID f;
@@ -164,9 +165,9 @@
     }
 
     /* Set General Bytes */
-    target_cls = e->GetObjectClass(o);
+    target_cls.reset(e->GetObjectClass(o));
 
-    f = e->GetFieldID(target_cls, "mGeneralBytes", "[B");
+    f = e->GetFieldID(target_cls.get(), "mGeneralBytes", "[B");
 
     TRACE("General Bytes Length = %d", sGeneralBytes.length);
     TRACE("General Bytes =");