Reputation: 2334
I have a widget im trying to update the TextView
using a timer:
public void onUpdate(Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
final int appWidgetId = appWidgetIds[i];
Intent clockIntent = new Intent(context, DeskClock.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, clockIntent, 0);
final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.digitalclock);
views.setOnClickPendingIntent(R.id.rl, pendingIntent);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
java.util.Date noteTS = Calendar.getInstance().getTime();
String time = "kk:mm";
String date = "dd MMMMM yyyy";
views.setTextViewText(R.id.tvTime, DateFormat.format(time, noteTS));
views.setTextViewText(R.id.tvDate, DateFormat.format(date, noteTS));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}, 0, 1000);// Update textview every second
}
}
Problem is, it only updates the once and never again afterwards. Where am I going wrong?
Upvotes: 0
Views: 700
Reputation: 133560
int _count=0;
_tv = (TextView) findViewById( R.id.textView1 );
_tv.setText( "red" );
_t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
@Override
public void run() {
_count++;
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
_tv.setText(""+_count);
}
});
}
}, 1000, 1000 );
Upvotes: 1
Reputation: 6197
You should use a Handler, to act on the UI Thread from a timertask.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
//Your code here
}});
}
}, 0, 1000);// Update textview every second
Also, you should initiate the Handler in onCreate() like this
handler = new Handler();
Upvotes: 2