Search code examples
androidmultithreadingjava-threads

wait() function not working in thread in android studio


Before asking the question let me tell you that I am new in android development. My question is regarding Threads and wait(); function. Right now I am trying to implement the thread which should change the color of text every 3 seconds but the program crashes as soon as I start it. Here is the code.

package care.client_application;

public class MainActivity extends AppCompatActivity {
   Thread Thread3=null; //Coloring thread
   public TextView Warning;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Warning= (TextView) findViewById(R.id.warning);
      UIHandler = new Handler();  //Initialization of handler

      this.Thread3= new Thread(new Thread3());
      this.Thread3.start();
   }

   class Thread3 implements Runnable{
      @Override
      public void run() {
         Warning.setTextColor(Color.rgb(200,200,0));
         wait(3000);
         Warning.setTextColor(Color.rgb(200,0,0));
      }
   }
}

Solution

  • I want to change the color of text every 3 seconds

    Why not use a Handler instead of Thread

    private Runnable task = new Runnable () {
        public void run() {
                //update textview color 
                Warning.setTextColor(Color.rgb(200,200,0));
                mHandler.postDelayed(task, 3000);  //repeat task
        }
    };
    

    Call it using:

     private Handler mHandler = new Handler();
    // call updateTask after 3 seconds
    mHandler.postDelayed(task, 3000);
    

    To stop the task:

        @Override
    protected void onPause() {
         mHandler.removeCallbacks(task);
         super.onPause();
    }