Reputation: 56199
I need to refresh TextViews every 5 seconds, I have created TimerTask( and set Activity like parameter in contrsuctor) but I got error that I can access widgets only from thread which created them.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.system_data_show);
currentActivity = this;
Timer timer = new Timer();
timer.schedule(new SystemTimerTask(currentActivity),500, 5000);
///////////////// text views from layout /////////////////////////////////////////////
TextView txtCapture = (TextView) this.findViewById(R.id.txtCapture);
txtCapture.setText("System Data");
TextView txtWorkAllowedValue=(TextView)this.findViewById(R.id.workAllowedValue);
TextView txtBusBroken0Value=(TextView)this.findViewById(R.id.busBroken0Value);
TextView txtBusBroken1Value=(TextView)this.findViewById(R.id.busBroken1Value);
TextView txtShortCircuit0Value=(TextView)this.findViewById(R.id.shortCircuit0Value);
TextView txtShortCircuit1Value=(TextView)this.findViewById(R.id.shortCircuit1Value);
TextView txtErrorConfigurationValue=(TextView)this.findViewById(R.id.errorConfigurationValue);
}
How to refresh this textViews on every 5 seconds ? Is there any way not to extend TimerTask, maybe o implement some interface ( I don't know which) so my SActivity extends Activity implements thatInterface ?
Upvotes: 0
Views: 333
Reputation: 1174
What you can do is create an inner AsyncTask class that will do do work in the background (get the data you want to refresh the textview with) and when that work is done in the background you post the result in the onPostExecute(you can update UI textview here) method.
After you have that AsyncTask inner class you do something in your timer like this every 5 seconds:
new MyAsyncTask.execute();
Upvotes: 1
Reputation: 111
You could use Activity.runOnUiThread(Runnable)
to update the UI components on the Timer thread as explained at the Android developer page and the API Doc page
If this doesn't fit what you require you could also use the View.post(Runnable)
method (also explain on the developer page above)
Upvotes: 1
Reputation: 74780
You can use Handler
and its postDelayed()
function. This way you will not need to create separate thread just for timing purposes. For the example see: Repeat a task with a time delay?
Upvotes: 1