Android Question How to store and retrive a list with SQLite

ostau

Member
Licensed User
Longtime User
Hi there,

I want to save a list of maps in a SQLite database field and then restore the list later.
I tried lots of different wasy, but finally, when I call the list from the database, it's not a list.

I tried to declare the database field as an BLOB -> the return value is a binary.
When I declare the database field as a string, I get back a string instead of a list.
I also converted the list to a JSON-Object, but still not possible to convert the stored and retrieved JSON back to a list of maps.

I created a very little solution to demonstrate the Problem. It's attached as zip.

B4X:
#Region Project Attributes
#ApplicationLabel: B4A Example
#VersionCode: 1
#VersionName:
'SupportedOrientations possible values: unspecified, landscape or portrait.
#SupportedOrientations: unspecified
#CanInstallToExternalStorage: False
#End Region
#Region Activity Attributes
#FullScreen: False
#IncludeTitle: True
#End Region
Sub Process_Globals
Dim SQL2 As SQL
End Sub

Sub Globals
End Sub

Sub Activity_Create(FirstTime As Boolean)
  SQL2.Initialize(File.DirDefaultExternal, "MyTest.db", True)
  Dim bSave As Button : bSave.Initialize("bSave") : Activity.AddView(bSave, 0, 0, 100%x, 50dip)
  bSave.Text = "Save"
  Dim bRetrieve As Button : bRetrieve.Initialize("bRetrieve") : Activity.AddView(bRetrieve, 0, 55dip, 100%x, 50dip)
  bRetrieve.Text = "Retrieve"
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub bSave_Click
  Dim m As Map : m.Initialize
  m.Put("Field1", 1)
  m.Put("Field2", 2)
  Dim l As List : l.Initialize
  l.Add(m)
 
'recreate the database
  DBUtils.DropTable(SQL2, "tbl1")
  Dim se As Map : se.Initialize
  se.Put("ID", DBUtils.DB_INTEGER)
  se.Put("ListOfMaps_String", DBUtils.DB_TEXT)
  se.Put("ListOfMaps_Object", DBUtils.DB_BLOB)
  DBUtils.CreateTable(SQL2, "tbl1", se, "ID")
 
  Dim li As List : li.Initialize
  Dim mi As Map : mi.Initialize
'save the list in database (here's the problem: how can I save the list to retrieve it later on?)
  mi.Put("ID", 1)
  mi.Put("ListOfMaps_String", l)
  mi.Put("ListOfMaps_Object", l)
  li.Add(mi)
  DBUtils.InsertMaps (SQL2, "tbl1", li)
End Sub

Sub bRetrieve_Click
  Dim cur As Cursor
  Dim o1 As Object
  Dim o2 As Object
  cur = SQL2.ExecQuery("SELECT ID, ListOfMaps_String, ListOfMaps_Object FROM tbl1")
  For i = 0 To cur.RowCount - 1
    cur.Position = i
    o1 = cur.GetString("ListOfMaps_String")
    o2 = cur.GetBlob("ListOfMaps_Object")
  Next
  Dim l1, l2 As List
  l1.Initialize
  l2.Initialize
  l1 = o1
  l2 = o1
  Log (l1) 'Now it's a string, not longer a list
  Log (l2)
End Sub

Thanks in advance for any advice!
 

Attachments

  • StoreListInSQL.zip
    11.2 KB · Views: 215

ostau

Member
Licensed User
Longtime User
Upvote 0
Top