I created this code. It works but I was wondering if there is an easier/optimized way to save a map to a KeyValueStore and retrieve it back from the KeyValueStore.
Main:
Starter:
Main:
B4X:
Sub Process_Globals
End Sub
Sub Globals
End Sub
Sub Activity_Create(FirstTime As Boolean)
Dim map1 As Map
map1.Initialize
map1.Put(1, "click")
map1.Put(2, "clack")
map1.Put(3, "snap")
map1.Put(4, "slappy")
SaveMapToKVS(Starter.kvs, map1, "key_string_1", "value_string_1")
Dim map2 As Map
map2.Initialize
map2 = LoadMapFromKVS(Starter.kvs, "key_string_1", "value_string_1")
Log("Test to see if it works:")
For i = 0 To map2.Size - 1
Log(map2.GetKeyAt(i) & " = " & map2.GetValueAt(i))
Next
End Sub
Sub LoadMapFromKVS(kvs As KeyValueStore, keyname As String, valuename As String) As Map
Dim map_new As Map
map_new.Initialize
Dim StringArray() As String
Dim StringArray2() As String
Dim s As String
Dim s2 As String
s = Starter.kvs.Get(keyname)
s2 = Starter.kvs.Get(valuename)
StringArray = Regex.Split(",", s)
StringArray2 = Regex.Split(",", s2)
For i = 0 To StringArray.Length - 1
map_new.Put(StringArray(i), StringArray2(i)) 'CInt(StringArray(i)) ?
Next
Return map_new
End Sub
Sub RemoveLastCharacter(s As String) As String
Return s.SubString2(0, s.Length - 1)
End Sub
Sub SaveMapToKVS(kvs As KeyValueStore, map1 As Map, keyname As String, valuename As String)
Dim s As String
For Each v As Int In map1.keys
s = s & v & ","
Next
s = RemoveLastCharacter(s)
Starter.kvs.Put(keyname, s)
s = ""
For Each v2 As String In map1.values
s = s & v2 & ","
Next
s = RemoveLastCharacter(s)
Starter.kvs.Put(valuename, s)
End Sub
Starter:
B4X:
Sub Process_Globals
Public kvs As KeyValueStore
End Sub
Sub Service_Create
kvs.Initialize(File.DirInternal, "datastore2")
End Sub
Last edited: