My timer has an issue, if I click on it around 3 times really fast ten the timer starts going backwards and forwards, its weird. My goal is so once I press on one listview item the other timer stops, or if I press on the same listview item that the timer pauses. But no luck, this is my code:
`
namespace floatingb.ViewModel
{
[AddINotifyPropertyChangedInterface]
public class TaskPageViewModel
{
//for navigation purposes
public INavigation _navigation;
public INavigation nav;
//dbconnector
private static DatabaseHelper dbhelper;
//command to add item to listview
private ICommand Addbtn;
//command to save teh item to database and observablecollection
private ICommand save;
//command to delete task that the user has pressed on.
private ICommand _DeleteSingleTask;
private ICommand StartPlayOrPauseButton;
private ObservableCollection<UserModel> items;
private List<UserModel> _itemsList;
//retrieve the item name in the UserModel class
private UserModel _itemName { get; set; }
//this is what will hold the listview items
private UserModel _SelectedListViewItem { get; set; }
//current task
private string task;
private string TimeStarted { get; set; }
//null because might not need to pass with parameter
public TaskPageViewModel(INavigation navigation = null)
{
//set the nevigation
nav = navigation;
//create new db
CreateNewDb();
}
//create new db
public static DatabaseHelper CreateNewDb()
{
//if null create new database
if (dbhelper == null)
{
dbhelper = new DatabaseHelper();
}
return dbhelper;
}
//add button to add new task
public ICommand AddButton
{
get => Addbtn ?? (Addbtn = new Command(() =>
{
nav.PushAsync(new NewItemAddView(this));
}));
}
//delete listview item task both from db and from observablecollection
public ICommand DeleteSingleTask
{
get => _DeleteSingleTask ?? (_DeleteSingleTask = new Command((UserModel) =>
{
//get selected listview item and convert it to userModel
_SelectedListViewItem = (UserModel)UserModel;
//remove from list
ListItems.Remove((UserModel)UserModel);
// MessagingCenter.Send(this, "xyz", ListItems.Count);
dbhelper.DeleteIndividualItem(_SelectedListViewItem.Id);
}));
}
//add task
public ICommand AddTask
{
get => save ?? (save = new Command(() =>
{
//current task
var currentTask = Task;
//current time on phone
var currentTime = DateTime.Now.ToString("HH:mm");
//create new user model
UserModel task = new UserModel
{
//set the item name to current task and datetimeset to current time
ItemName = currentTask,
DateTimeSet = currentTime,
SelectedColor = "#4286f4"
};
//add to listitems (ObservableCollection
ListItems.Add(task);
//insert in db the task
dbhelper.InsertItem(task);
}));
}
public ICommand PlayOrPauseButtonPressed
{
get => StartPlayOrPauseButton ?? (StartPlayOrPauseButton = new Command((UserModel) =>
{
//var SelectedItemId = ListItems.Where(i => i.Id == (int)UserModel);
UserModel selectedUser = (UserModel)UserModel;
//if not equal to purple colour set it to purple colour
if(!selectedUser.DefaultColor.Equals("#f420db"))
{
selectedUser.DefaultColor = "#f420db";
}
//update database to add new colour value
dbhelper.UpdateItem(selectedUser);
//start the timer
StartTimer(selectedUser);
}));
}
public string MyTextColor
{
get { return "#42f4ad"; }
}
//return the task
public string Task
{
get { return task; }
set
{
task = value;
}
}
//return only item name
public string ItemName
{
get => _itemName.ItemName;
set
{
_itemName.ItemName = value;
}
}
public string TimeStart
{
get => TimeStarted;
set
{
TimeStarted = value;
}
}
public UserModel SelectedListViewItem
{
get { return _SelectedListViewItem; }
set
{
if (_SelectedListViewItem != null)
_SelectedListViewItem.Selected = false;
_SelectedListViewItem = value;
//set to false first incase its true already.
// _SelectedListViewItem.Selected = false;
//if bool is item selected is false
if (_SelectedListViewItem.Selected == false)
{
// then set the state to true since the item has been pressed.
// _SelectedListViewItem.Selected = true;
//MessagingCenter.Send<TaskPageViewModel, string>(this, "Detail", _SelectedListViewItem.ItemName);
}
}
}
//this is used to store the "previously" selected item
UserModel um = new UserModel();
//once the user presses on a listview item then start the timer
public void StartTimer(UserModel selectedListViewItem)
{
//new stopwatch object to start time
Stopwatch timeElapsed = new Stopwatch();
//new date time
DateTime dt = new DateTime();
//set to current date time
dt = DateTime.Now;
//used to check if time of day is AM/PM
string IsAmOrPM = "";
//store the total elapsed time because when we stop timer so text can stay
string totalElapsedTime = "";
bool hasDeviceTimerStopped = false;
//this checks to see if there is no content inside of this UserModel
if (um.Id == 0)
{
um = selectedListViewItem;
}
//if objects arent equal then do the following
if (!um.Equals(selectedListViewItem))
{
//stop timer temporarily since new item has started
timeElapsed.Stop();
//set this variable to the new item since new item has been selected
um = selectedListViewItem;
//set to current time spent on item
um.DateTimeSet = totalElapsedTime;
}
//if greater than 19 set to pm
if(dt.Hour > 19)
{
IsAmOrPM = "PM";
}
//if less than 19 set to am
else if(dt.Hour < 19)
{
IsAmOrPM = "AM";
}
if (um.Equals(selectedListViewItem) && hasDeviceTimerStopped == false)
{
//start the stopwatch
timeElapsed.Start();
//need to make a bool here that allows only once for timer to start make a if statement here
//start timer
StartTimer(selectedListViewItem, timeElapsed, IsAmOrPM, hasDeviceTimerStopped);
}
}
public void StartTimer(UserModel u, Stopwatch s,string ampm, bool timerStopped)
{
Device.StartTimer(TimeSpan.FromMilliseconds(1000), () =>
{
//update text to show the current time spent on task.
u.DateTimeSet = string.Format("{0:00}:{1:00}:{2:00} ", s.Elapsed.Hours, s.Elapsed.Minutes, s.Elapsed.Seconds) + ampm;
//if objects are not same then this means user has selected a new object and must stop the timer
if (u.Id != um.Id)
{
timerStopped = true;
u.DateTimeSet = "test";
return false;
}
//return true since objects are same
return true;
});
}
//observablecollection that contains UserModel items
public ObservableCollection<UserModel> ListItems
{
get => items;
set
{
items = value;
}
}
//bind items to listview
public void BindItems()
{
_itemsList = dbhelper.GetAllItemsData().ToList();
ListItems = new ObservableCollection<UserModel>(_itemsList);
//loop through list items and if id is less than 0 set it to default colour which is below (this is used so when the user leaves this page the timer stops)
for (int i = 0; i < items.Count; i++)
{
if (items[i].Id > 0)
{
items[i].DefaultColor = "#59f441";
}
}
}
}
}
`