Search code examples
androidonclicklistenertimedelaypostdelayed

postDelayed OnClickListener is not working


I am trying to implement a delay on button click, each second I need to remove one item from a list called solved_cells, the list initially has 16 items. below is what I did:

solve_all.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                   while (solved_cells.size()>=1) {
                       v.postDelayed(new Runnable() {
                           @Override
                           public void run() {
                               //Execute code here
                        solved_cells.remove(solved_cells.size() - 1);
                          }
                       }, 1000L);

                    }
        }
    });

but each time I debug , I see the code reach to :

v.postDelayed(new Runnable() {

and doesn't touch the public void run() { function, Your suggestions are highly appreciated.


Solution

  • i don't know exactly what your problem in your code but you can use timer instead like this by creating TimerTask class

       Timer timer;
       MyTimerTask timerTask;
    private class MyTimerTask extends TimerTask {
    
        @Override
        public void run() {
            try {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (solved_cells.size() > 0) {
                            solved_cells.remove(solved_cells.size() - 1);
                        } else {
    
                            timer.cancel();
                            timer.purge();
                        }
                    }
                });
            } catch (Exception e) {
                // e.printStackTrace();
            }
        }
    }
    

    and in your listener you can declare it like this

    solve_all.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          timerTask = new MyTimerTask();
          Timer t = new Timer();
          t.schedule(timerTask , 1000L);
    
        }
    });