Reputation: 6888
I am writing a small program to update TextView in every 5 seconds. But I am unable to update my textview's text in every 5 seconds, especially when it comes to last arraylist item, like: C in below code
I am following this tutorial
public class MainActivity extends Activity {
Timer timer;
MyTimerTask myTimerTask;
List<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textCounter = (TextView)findViewById(R.id.counter);
timer = new Timer();
myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 1000, 5000);
....
list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
runOnUiThread(new Runnable(){
@Override
public void run() {
for(int i=0; i<list.size(); i++) {
textCounter.setText(list.get(i).toString());
}
}});
}}
Upvotes: 4
Views: 827
Reputation: 1386
Change your MyTimerTask class as given below.
private int position = 0;
class MyTimerTask extends TimerTask {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (position >= list.size()) {
position = 0;
}
textCounter.setText(list.get(position).toString());
position++;
}
});
}
}
Upvotes: 1
Reputation: 1277
here I have Some Code Snippet which is just update Textview After every 5 Seconds.
Step 1: First you are just making one saperate method where Textview is Update like following.
private void updateTextView(){
/**
* Write Your Textview Update Code
*/
}
Step 2 Declare object of Runnable class which is Just Call updateTextview method after some specific time.
Runnable run = new Runnable() {
@Override
public void run() {
updateTextView();
}
};
Step 3 you can Start this runnable using following code.
YOUR_TEXTVIEW.postDelayed(run,5000);
I hope you are clear with my Idea.
Best of Luck
Upvotes: 1
Reputation: 12861
Instead of using TimerTask
You should use Handler
for Updating TextView
.
Handler mHandler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
@Override
public void run() {
count++;
textCounter.setText(list.get(count).toString());
mHandler.postDelayed(this, 5000); // five second in ms
}
};
mHandler.postDelayed(runnable, 1000);
I hope this helps you.
Upvotes: 2
Reputation: 10299
Don't iterate list every time run method called. Instead get one item from list and set it to TextView.
private int count =0;
private class MyTimerTask extends TimerTask {
@Override
public void run() {
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(list.get(count%list.size).toString());
count++;
});
}
}
}
Upvotes: 2