Increment Android Widget TextView every second using System.Timers

  android, android-widget, c#

I am trying to create a widget that displays the number of books entered today and the time since the last entry of a book in an SQLite DB.

I’m trying to use System.Timers to fire the timer and every second update the UI.

The problem I have is that no text is displayed. The time difference displayed should increase by one second for each second that there is no new book entered since the last book record.

class widget_class : AppWidgetProvider
    {         
        private Book latestBook;
        public override void OnUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
        {                
            var me = new ComponentName(context, Java.Lang.Class.FromType(typeof(widget_class)).Name);
            appWidgetManager.UpdateAppWidget(me, BuildRemoteViews(context, appWidgetIds));
        }

        private RemoteViews BuildRemoteViews(Context context, int[] appWidgetIds)
        {
            var widgetView = new RemoteViews(context.PackageName, Resource.Layout.widget);
            
            Device.StartTimer(TimeSpan.FromSeconds(1), () =>
            {
                Device.BeginInvokeOnMainThread(() => SetTextViewText(widgetView));
                return true;
            });

            return widgetView;
        }

        private void SetTextViewText(RemoteViews widgetView)
        {       
            if (latestBook == null)
            {
                if (App.Database.GetTableCount() > 0)
                {
                    latestBook = App.Database.GetRecentDate().FirstOrDefault();
                    widgetView.SetTextViewText(Resource.Id.textView1, "Today" + "rn" + App.Database.GetDailyBookCount() + "rn" + "rn" + "Last Book" + "rn" + CalculateDifference());
                }
                else
                {
                    widgetView.SetTextViewText(Resource.Id.textView1, "Today" + "rn" + 0 + "rn" + "rn" + "Last Book" + "rn" + "00:00:00");
                }
            }
            else
            {
                widgetView.SetTextViewText(Resource.Id.textView1, "Today" + "rn" + App.Database.GetDailyCount() + "rn" + "rn" + "Last Book" + "rn" + CalculateDifference());
            }
        }

        private string CalculateDifference()
        {
            var timeDifference = DateTime.Now - latestBook.BookSaveTime;
            return (int)timeDifference.TotalHours < 24
                ? timeDifference.ToString(@"hh:mm:ss")
                : (int)timeDifference.TotalHours + timeDifference.ToString(@":mm:ss");
        }

Source: Android Questions

LEAVE A COMMENT