title: Android JNI ReleaseByteArrayElements does not work
body: <p>i have got a problem at using Android JNI. I call a java method from native C. Everything works fine, BUT after a few seconds the APP crashes, because the maximum of 512 entrys of JNI refs is full (or the memory is full).</p>
  
  <p>Here is my code:</p>
  
  <pre><code>int jniBluetoothSend( TJNIAdapter *pAdapter, byte *data, int dwLength )
  {
  JNIEnv *pEnv;
  JavaVM *pVm = NULL;
  jclass cls;
  jmethodID methodId;
  int nRet;
  jbyteArray aData;
  
  if ( pAdapter )
  {
     pVm = pAdapter-&gt;pVm;
     ( *pVm )-&gt;AttachCurrentThread( pVm, &amp;pEnv, NULL );
  
     if ( pAdapter-&gt;pClasses != NULL &amp;&amp; pAdapter-&gt;pClasses-&gt;hgs_bluetooth != NULL )
     {
        // get function
        methodId = ( *pEnv )-&gt;GetMethodID( pEnv, pAdapter-&gt;pClasses-&gt;hgs_bluetooth, "write", "([BI)I" );
        if ( methodId )
        {
           aData = ( *pEnv )-&gt;NewByteArray( pEnv, dwLength);
           ( *pEnv )-&gt;SetByteArrayRegion( pEnv, aData, 0, dwLength, data);
           // write Data to device
           nRet = ( *pEnv )-&gt;CallIntMethod( pEnv, g_hgsBthObject, methodId, aData, dwLength );
  
           // and delete Reference -&gt; so GC can cleanup
           ( *pEnv )-&gt;DeleteLocalRef( pEnv, aData );
        }
     }
     //( *pVm )-&gt;DetachCurrentThread( pVm ); -&gt; // crashes as soon as getting called
  }
  return nRet;
  </code></pre>
  
  <p>}</p>
  
  <p>Everytime "ReleaseByteArrayElements()" gets called a warning shows up in Android Log from dalvik:</p>
  
  <pre><code>JNI: unpinPrimitiveArray(0x428e84a8) failed to find entry (valid=1)
  </code></pre>
  
  <p>So, i think, the problem is, that the created array is not getting freed. But I don't know, how to do this in the right way.</p>
  
  <p>Can anyone help me with this? 
  Thanks!</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have done a several tests.
  If i add the <code>DetachCurrentThread</code> function to the bottom of the second if(), the APP crashes, if <code>DetachCurrentThread</code> is getting called.</p>
  
  <p>But i have added <code>DeleteLocalRef</code> in an other function, and the APP does not crash anymore. </p>
  
  <p>So my question is: Do i have to call <code>DetachCurrentThread</code> in every function i call <code>AttachCurrentThread</code> or is it enough if i call that once to the end of the APP?</p>
  
  <p><em>Also updated the Code</em></p>