title: Using NDK from C++ updating Android UI
body: <p>My question is related directly to this post: <a href="https://groups.google.com/forum/#!topic/android-ndk/291sBdkITyI" rel="nofollow">https://groups.google.com/forum/#!topic/android-ndk/291sBdkITyI</a></p>
  
  <p>Basically, I have an application written in C++ compiled with the NDK with a basic Android (activity). I have a textview (in Java) that needs to be updated when something happens in the c++ side (say for example a state change). I would like to call Java from C++ and update the textview when the state changes.</p>
  
  <p>In the link above, the code they used was (probably pseudo code):</p>
  
  <pre><code>public class Example extends Activity{    
  
      Handler handler = new Handler() {
  
           @Override
           public void handleMessage(Message msg) {
               this.currentDownloadField.setText(""+ msg.what);
           }
  
      }
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          // whatever
      }   
  
      public static void sendMessage(int  id){ 
           handler.sendEmptyMessage(id); // just the what() is filled with the id
      }
  }
  </code></pre>
  
  <p>And calling from C++ would be</p>
  
  <pre><code>void sendMessage(char* buffer, int bufferlen) {
      JNIEnv *env = NULL;
      jmethodID mid = NULL;
      jbyteArray message;
  
      jint res = (jjvm-&gt;AttachCurrentThread(&amp;jjvm, &amp;env, NULL));
  
      if (res &gt;= 0) {
          message = (*env)-&gt;NewByteArray(env, bufferlen);
          (*env)-&gt;SetByteArrayRegion(env, message, 0, bufferlen, (const jbyte *) ((BYTE*) buffer));
          mid = (*env)-&gt;GetStaticMethodID(env, jcls, "sendMessage", "([B)V");
  
          // Mid &lt;= 0 ? Not found : OK
          if (mid &gt; 0) {
          (*env)-&gt;CallStaticVoidMethod(env, jcls, mid, message);
          }
      }
  }
  </code></pre>
  
  <p>The problem is using "handler" in the activity from a static function does not work (because it is not static). If it was static, then how does "this.currentDownloadField" get referenced?</p>
  
  <p>I also tried just calling a public function from c++ </p>
  
  <pre><code>public void update(String message) {
      Log.i("logging", "Hit here")
      mMyTextField.setText(message);
  }
  </code></pre>
  
  <p>When C++ calls the Java function "update", the log hits (in logcat) but the textview does not update. Maybe it is an issue with threads but I have no idea how to update the textfield correctly.</p>
  
  <p>The other option is to poll and have Java call C++ to read a variable (state) however that is tedious and not good programming practice.</p>
  
  <p>Any suggestions to tackle this?</p>
  
  <p>Thanks in advance.</p>