I have been facing a problem that I can't seem to solve. I have a SQL table that I want to update regularly with the timer function. The goal is to automatically update existing records or insert records if it is not existing. The code below is what I came up with but it is not working, I just can't get it to update a record, instead, it creates multiple records. I want the code to check if a record exists (using the package name to check the table) and update if it exists or insert new record into the table if it does not (in a case of a newly installed app)
To better understand the context in which I am using this code, the routine is meant to check the app usage of each app every 2 seconds and update the SQL data accordingly.
To better understand the context in which I am using this code, the routine is meant to check the app usage of each app every 2 seconds and update the SQL data accordingly.
B4X:
Sub Timer1_Tick
For i = 0 To usage1.Size -1
Dim us As UsageStats = usage1.Get(i)
Dim package As String = us.PackageName
Dim time As String = DateTime.Time(us.lasttimeused)
Dim date As String = DateTime.Date(us.LastTimeUsed)
Dim foregroundtime As Long = us.TotalTimeInForeground
Dim Cursor As ResultSet = sql.ExecQuery("SELECT * FROM AppList WHERE PackageName = ' "& package &" '")
If Cursor.RowCount > 0 And date = DateTime.Date(DateTime.Now) Then
sql.ExecNonQuery("UPDATE AppList SET LastTimeUsed = ' "& time & " ', LastDateUsed = ' "& date & " ', TotalTime = ' "& totaltime & " ', foregroundtime = ' "& foregroundtime &" ' WHERE PackageName = ' "& package &" ';")
Log(Cursor.RowCount)
If Cursor.RowCount = 0 And date = DateTime.Date(DateTime.Now) Then
sql.ExecNonQuery2("INSERT INTO AppList VALUES(?,?,?,?,?)", Array As String(package,time,date,totaltime,foregroundtime))
Log(Cursor.RowCount)
End If
End If
Next
sql.ExecQuery("SELECT * FROM AppList ORDER BY LastTimeUsed DESC")
End Sub