[QUESTION] Time needed by file operation and SQL operation

Ramirez

Member
Licensed User
Longtime User
Hello.

Juste for my information (and because I have some problems), is a file operation (read or write) is more quick or not than an SQL operation ?
Of course, the SQL operation is on a little base (I suppose the size of the database is important).
I have this question because I use a SQL database and a file into my application, and for each file operation, I have some strange results.
For example in my application, the file is read and the result was write in a list (initialized). Immediatly after, I check a value stored in this list and launch an activity (depend of the result of course). The value is a date in string type, so to use it I have to "parse" it. During the execution, the program stop and tell me that the value "" cannot by parsed, but few second after, the activity on my device change (like if the test finaly was done after these few seconds).
When I run the program step by step, no problem, the test is done correctly without error (it's normal in my opinion, because we have enought time to read the file).

I cannot put my code in this thread, I already change the program to test the fonction with my SQL database, but I want to understand what's hapened ?

Thanks for attention, I hope my speech is understandable :)
 

Ramirez

Member
Licensed User
Longtime User
Ok I will try to paste my code and explain the problem. The entire project is in the zip file attached.

B4X:
Sub Activity_Create(FirstTime As Boolean)
   CreationFichierSQL
   
   'Récupération des infos utilisateur
   Dim curseur As Cursor
   curseur = SQL1.ExecQuery("SELECT * FROM Utilisateur")
   If curseur.RowCount = 0 Then StartActivity("User")
   curseur.Position = 0
   Utilisateur = curseur.GetString("Nom")
   Objectif = curseur.GetInt("Objectif")
   PoidsDepart = curseur.GetDouble("Poids de départ")
   Taille = curseur.GetInt("Taille")
   DateNaissance = curseur.GetString("Date de naissance")
   Sexe = curseur.GetString("Sexe")
   Activite = curseur.GetInt("Activité")
   Points = curseur.GetInt("Points")

   
   ' Création de la liste des groupes d'aliments
   groupe.Initialize
   groupe.AddAll(Array As String("Accompagnements apéritif"))
   [...]
   groupe.AddAll(Array As String("Viandes et volailles"))

   ' Affichage de la page Main et création du menu
   Activity.LoadLayout("formMain")

   ' Affichage de la date du jour
   DateTime.DateFormat = "dd/MM/yyyy"
   lblDate.Text=DateTime.Date(DateTime.Now)
   
   'Création du titre de la liste déroulante de la vue agenda
   If panTitre.IsInitialized=False Then
      panTitre.Initialize("")
      Dim l As Label
      l.Initialize("panTitre")
      l.Color=Colors.LightGray   
      l.TextColor=Colors.Black   
      l.TextSize=16 
      l.Gravity = Gravity.LEFT   
      l.Text = "Description"
      panTitre.AddView(l, 0, 0, 400, 40)   
      l.Initialize("panTitre")
      l.Color=Colors.LightGray   
      l.TextColor=Colors.Black   
      l.TextSize=16 
      l.Gravity = Gravity.LEFT   
      l.Text = "Points"
      panTitre.AddView(l, 400, 0, 80, 40)   'ajout de l à panTitre
      Activity.AddView(panTitre, scrAgenda.Left, scrAgenda.Top - 40, scrAgenda.Width, 40) 
   End If

   'Création de la liste déroulante de la vue agenda
   panTable = scrAgenda.Panel
   panTable.Color=Colors.black
   
End Sub

Sub Activity_Resume
   ' Mise à jour table
   Activity.Title = "FlexiPoint - " & Utilisateur
   MiseAJourTable
End Sub

Sub MiseAJourTable()
   ' Affichage du capital point
   Dim curseur As Cursor
   lblCapitalPts.Text = Points
   lblPtsRestants.Text = Points
   
   'Affichage des points bonus
   lblPtsBonus.Text = 0

   ' Effacement de la table
   For i= panTable.NumberOfViews-1 To 0 Step -1
      panTable.RemoveViewat(i)
   Next
   
   ' Récupération des enregistrement 
   curseur = SQL1.ExecQuery("SELECT Clé, Aliment, Points, Repas FROM Agenda WHERE Date = '" & lblDate.Text & "' AND Poids IS NULL ORDER BY Repas")
   numeroDeLigne=0
   For i=0 To curseur.RowCount-1
      Dim ligne(2) As String
      Dim nIndex As Int
      Dim couleur As Int
      curseur.Position = i
      ligne(0)=curseur.GetString("Aliment")
      ligne(1)=Fonction.Arrondi(curseur.GetDouble("Points"))
      nIndex=curseur.GetInt("Clé")
      Select curseur.GetInt("Repas")
         Case 1
         couleur=Colors.Yellow
         Case 2
         couleur=Colors.Red
         Case 3
         couleur=Colors.Blue
         Case 4
         couleur=Colors.Green
      End Select
      AjoutLigne(ligne,nIndex,couleur)
      lblPtsRestants.Text = lblPtsRestants.Text - ligne(1)
   Next
   curseur.Close
   dateDuJour = lblDate.Text
   panTable.Height=numeroDeLigne*40

End Sub

Sub AjoutLigne(valeur() As String, ind As Int, couleur As Int)
   'ajoute une ligne à la Table composée de 2 colonnes
   
   If valeur.Length<>2 Then Return
   Dim l1 As Label
   Dim l2 As Label
   
   'Première colonne
   l1.Initialize("cellule")
   l1.Text=valeur(0)
   l1.Gravity=Gravity.LEFT
   l1.TextSize=18
   l1.TextColor=Colors.Black
   l1.Color=couleur
   Dim ligneColonne1 As coordonnee
   ligneColonne1.Initialize
   ligneColonne1.col = 0
   ligneColonne1.row = numeroDeLigne
   ligneColonne1.clef = ind
   l1.Tag = ligneColonne1
   panTable.AddView(l1, 0, 40 * numeroDeLigne, 400, 38)
   
   'Deuxième colonne
   l2.Initialize("cellule")
   l2.Text=valeur(1)
   l2.Gravity=Gravity.CENTER_HORIZONTAL
   l2.TextSize=18
   l2.TextColor=Colors.Black
   l2.Color=couleur
   Dim ligneColonne2 As coordonnee
   ligneColonne2.Initialize
   ligneColonne2.col = 1
   ligneColonne2.row = numeroDeLigne
   ligneColonne2.clef = ind
   l2.Tag=ligneColonne2
   panTable.AddView(l2, 400, 40 * numeroDeLigne, 80, 38)
   
   'saut de ligne
   numeroDeLigne=numeroDeLigne+1
   panTable.Height=numeroDeLigne*40
      
End Sub

Sub CreationFichierSQL
   'Initialisation base SQL 
   '------------------------
   If File.Exists(File.DirDefaultExternal, "Database.db") = False Then 
      SQL1.Initialize(File.DirDefaultExternal, "Database.db", True)
   Else
      SQL1.ExecNonQuery("DROP TABLE IF EXISTS Utilisateur")
      SQL1.ExecNonQuery("DROP TABLE IF EXISTS Agenda")
      SQL1.ExecNonQuery("DROP TABLE IF EXISTS Aliments")
      'SQL1.ExecNonQuery("DROP TABLE IF EXISTS xxx")
   End If

   'Création table agenda
   '----------------------
   SQL1.ExecNonQuery("CREATE TABLE [Agenda] ([Clé] INTEGER PRIMARY KEY, [Date] TEXT, [Aliment] TEXT, [CléAliment] INT, [Repas] INT, [Points] REAL, [Qté] REAL, [Poids] REAL, [DIVERS] TEXT)")
   SQL1.ExecNonQuery("INSERT INTO Agenda VALUES (NULL, '01/07/2011', NULL, NULL, NULL, NULL, NULL, 112, NULL)")
   SQL1.ExecNonQuery("INSERT INTO Agenda VALUES (NULL, '01/08/2011', NULL, NULL, NULL, NULL, NULL, 110, NULL)")
   
   'Création table utilisateur 
   '---------------------------
   SQL1.ExecNonQuery("CREATE TABLE [Utilisateur] ([Nom] TEXT, [Date de naissance] TEXT, [Sexe] TEXT, [Taille] TEXT, [Poids de départ] REAL, [Activité] INT, [Objectif] REAL, [Points] INT)")
   
   'Création table répétition
   '--------------------------
   ' a faire
   
   ' Effacement et recréation de la table Aliments (une ligne par portion)
   '----------------------------------------------------------------------
   query="CREATE TABLE [Aliments] ([Clé] INTEGER PRIMARY KEY, [Type] TEXT, [Nom] TEXT, [Qté] INTEGER, [Portion] TEXT, [Points] REAL)"
   SQL1.ExecNonQuery(query)
   'remplissage table avec des valeurs par défaut
   SQL1.ExecNonQuery("INSERT INTO Aliments VALUES (NULL, 'Accompagnements apéritif','Cacahuètes grillées salées', 15, 'Pièce(s)', 0.440407)")
   [...]
End Sub

Here the result of the log
B4X:
main_activity_create (B4A line: 78)


Utilisateur = curseur.GetString("Nom")

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
   at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
   at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
   at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
   at anywheresoftware.b4a.sql.SQL$CursorWrapper.GetString(SQL.java:260)
   at com.flexipoint.main._activity_create(main.java:282)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:507)
   at anywheresoftware.b4a.BA.raiseEvent2(BA.java:105)
   at com.flexipoint.main.afterFirstLayout(main.java:84)
   at com.flexipoint.main.access$100(main.java:16)
   at com.flexipoint.main$WaitForLayout.run(main.java:72)
   at android.os.Handler.handleCallback(Handler.java:587)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:123)


   at android.app.ActivityThread.main(ActivityThread.java:3691)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:507)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
   at dalvik.system.NativeStart.main(Native Method)
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
** Activity (main) Pause, UserClosed = false **


** Activity (user) Create, isFirst = true **


** Activity (user) Resume **
During the start of the application, an error message occur about the line 78 (Utilisateur = curseur.GetString("Nom")).
After few seconds, the device screen shitch to black (no error message, nothing...), and if I clic one the IDE on the "play" icon (to continue the program), the program continue.

The error line is:
B4X:
   If curseur.RowCount = 0 Then StartActivity("User")
   curseur.Position = 0
   [COLOR="Red"]Utilisateur = curseur.GetString("Nom")[/COLOR]
It's very strange because the line
B4X:
If curseur.RowCount = 0 Then StartActivity("User")
is not executed "at the good time" (the activity "user" is launch, i'm sure of that, because a breakpoint stop the execution of the program, but after the program continue to execute the line under the test !)

I'm sure I'm not clear, sorry, I'm French and my english is very poor ! :sign0085:
 

Attachments

  • test.zip
    29.7 KB · Views: 188
Upvote 0
Top