Skip to content Skip to sidebar Skip to footer

Android Backgroud Thread Cannot Change Textview Through Handler

I am unable to understand why my background thread is not able to change the content of textView(txtName) after screen orientation is changed. If I make txtname as static it works,

Solution 1:

Try runOnUiThread:

@OverridepublicvoidonConfigurationChanged(Configuration newConfig){ 
    super.onConfigurationChanged(newConfig); 

    Handler handler = newHandler() {
      publicvoidhandleMessage(Message msg) {
         runOnUiThread(newRunnable() {
             @Overridepublicvoidrun() {
                 // get the bundle and extract data by keyBundle b = msg.getData();
                 String key = b.getString("My Key");
                 txtName.setText( "Item " + key);
                 txtName.setVisibility(View.VISIBLE);
                 Log.e("TEST MESSAGE",  txtName.getText().toString());
             }
         });
      }
   };
} 

Solution 2:

Create your OnClickListener as a fixed Class and then apply it as:

MyListenermyListener=newMyListener();

btnClose.setOnClickListener(myListener);

In this way the txtName variable musn't be set as final

Solution 3:

Your UI can only be updated by the UI thread. Try something like this to ask your UI thread to update the interface as soon as possible. This way i think you can avoid using a handler.

btnClose.setOnClickListener(newView.OnClickListener() {
        publicvoidonClick(View arg0) {
              //Closing SecondScreen ActivityThread background = newThread(newRunnable() {
                   @Overridepublicvoidrun() {
                    for (int i = 0; i < 30; i++) {
                     try {
                      Thread.sleep(1000);
                      final String val = "My Value: " + String.valueOf(i);
                      // ask UI thread to make the changes as soon as possible
                      txtName.post(newRunnable(){
                     publicvoidrun(){
                              txtName.setText( "Item " + val);
                              txtName.setVisibility(View.VISIBLE);
                         });
                      } catch (Exception e) {
                      Log.d("Error", e.toString());
                     }
                    }
                   }
              });
              background.start();
        }
    });

Post a Comment for "Android Backgroud Thread Cannot Change Textview Through Handler"