B4X:
B4XMainPage - 437: Object reference not set to an instance of an object.
B4XMainPage - 435: Unknown member: get
B4XMainPage - 434: Index was out of range. Must be non-negative and less than the size of the collection.<br />Parameter name: index
B4XMainPage - 420: Current declaration does not match previous one.
Code:
Private Sub FetchFromAPIAndSearch(paycode As String)
Dim j As HttpJob
j.Initialize("", Me)
j.Download("https://myapi//")
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
Try
Dim parser As JSONParser
parser.Initialize(j.GetString)
' Get the array from JSON
Dim students As List = parser.NextArray
Dim found As Boolean = False
' Check if the list is not empty
If students.Size > 0 Then
' Iterate through the list using For Each
For Each student As Map In students
' Try to get Paycode safely
Dim StudentPaycode As String = ""
If StudentPaycode = paycode Then
found = True
' Get student details safely
Dim regNo As String = ""
Dim name As String = ""
Dim className As String = ""
Dim stream As String = ""
Dim account As String = ""
Try
regNo = student.Get("RegNo")
Catch
regNo = ""
End Try
Try
name = student.Get("Name")
Catch
name = ""
End Try
Try
className = student.Get("Class")
Catch
className = ""
End Try
Try
stream = student.Get("Stream")
Catch
stream = ""
End Try
Try
account = student.Get("Account")
Catch
account = ""
End Try
Dim dateFetched As String = DateTime.Date(DateTime.Now)
'Save to database - using local db variable
db.BeginTransaction
Try
Dim cursor As ResultSet = db.ExecQuery2("SELECT id FROM students WHERE reg_no = ?", Array As String(regNo))
If cursor.NextRow Then
Dim updateQuery As String = "UPDATE students SET Name = ?, Class = ?, Stream = ?, account = ?, Paycode = ?, date_fetched = ? WHERE reg_no = ?"
db.ExecNonQuery2(updateQuery, Array As String(name, className, stream, account, StudentPaycode, dateFetched, regNo))
Else
Dim insertQuery As String = "INSERT INTO students (reg_no, Name, Class, Stream, account, Paycode, date_fetched) VALUES (?, ?, ?, ?, ?, ?, ?)"
db.ExecNonQuery2(insertQuery, Array As String(regNo, name, className, stream, account, StudentPaycode, dateFetched))
End If
cursor.Close
db.TransactionSuccessful
UpdateStatus
Catch
db.Rollback
Log("Error saving: " & LastException.Message)
End Try
ShowStudentDetails(regNo, name, className, stream, account, StudentPaycode)
lblStatus.Text = $"✓ Paycode found for ${name}"$
Exit
End If
Next
End If
'If Not found Then
' xui.MsgboxAsync($"No student found with Paycode: ${paycode}"$, "Not Found")
'lblStatus.Text = "✗ Paycode not found in API"
'End If
Catch
lblStatus.Text = "Error parsing data: " & LastException.Message
Log("Error: " & LastException.Message)
End Try
Else
lblStatus.Text = "Error fetching data: " & j.ErrorMessage
xui.MsgboxAsync("Failed to fetch data from API", "Error")
End If
j.Release
End Sub