Search code examples
androidtimerandroid-listviewhandlertextview

Updating the List UI with Timer


I am trying to update the ListView with timer. I have implemented the android UI timer but my problem is how to use it for ListView where I need to update each row of the list after a certain interval. How does the handler will update the each row of the list (i.e. suppose a TextView is inside the each row where I'll display the updated values)?

public class ListAdapter extends BaseAdapter {

    private List<String> messages;
    private Context mContext;

    public ListAdapter(Context context , List<String> messages){
        this.messages   =  messages;
        mContext   =  context;
    }

    @Override
    public int getCount(){
        return messages.size();
    }

    @Override
    public Object getItem(int location){
        return messages.get(location);
    }

    @Override
    public long getItemId(int index){
        return index;
    }

    @Override
    public View getView(int index , View convertView, ViewGroup viewGroup){

            TextView time = new TextView(mContext);

                //udpate the time.setText() using timer
        convertView = (View)time

        return convertView;
    }   

Solution

  • Create a customHandler class that extends Handler class and call the sendEmptyMessage() of handler from the timer run() method.

    In the Handler class override the handleMessage and update your listview values and call adapter.notifyDataSetChanged() which will refresh the listview with the updated values.

    Here is the sample code :

    Timer timer = new Timer();
    CustomTimerTask customTimerTask = new CustomTimerTask();
    customTimerTask.run();
    timer.scheduleAtFixedRate(customTimerTask, 1000 , 1000);
    
    class CustomTimerTask extends TimerTask {
    
        @Override
        public void run() {
            myHandler.sendEmptyMessage(0);
        }
    }
    
        class CustomHandler extends Handler{
    
    
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            /// Do your listview update thing
     }
    

    }