Muhammed Almaz Muhammed Almaz - 3 months ago 25
Android Question

Android Timer Task Issue

I need a timer when Loaded ListView . Like " Waiting [(Timer) 42] Seconds for buy elements " I want to show users Textview Like it. I can't use Thread in ListView...

I get Error from runOnUiThread. Why ? I cant use timer In Listview.

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

final TextView LblTime;

inflater=(LayoutInflater)Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.test,parent,false);

LblTime=(TextView)view.findViewById(R.id.LblFragmentAnaListViewKalanSure );

Timer T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Context.getApplicationContext().runOnUiThread(new Runnable() {
@Override
public void run() {
long Time= MyTime.get(position).getTime() - (new Date()).getTime();
long Sec= Time/ 1000 % 60;
long Min= Time/ (60 * 1000) % 60;
LblTime.setText(Min+":"+Sec);
}
});
}
}, 1000, 1000);
return view;
}

Answer

Try this.. for call atfer 42 sec..

(new Handler()).postDelayed(new Runnable() {

    public void run() {
        // do you want
     }
 }, 42000);

if every sec you need to than do it..

This is using the Handler

Initialize..

Handler handler = new Handler();

Import

import android.os.Handler;

call this for..

 handler.postDelayed(yourtask,42*1000);



 private Runnable yourtask = new Runnable() {
    public void run() {

      // Run your code..
        handler.removeCallbacks(yourtask);
        handler.postDelayed(yourtask, 42*1000); // again start...

    }
};

This is Using Timer every one second....

final Handler handler = new Handler();
Timer timer = new Timer();
private int DELAY = 1000 * 60 * 1;

call this

   timer.scheduleAtFixedRate(doAsynchronousTask, 0, DELAY);

in class

  TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
             // your code


                }

            });


        }
    };