B4J Question Map Key turned string at load from file.readmap - Advice/Tip required.

roerGarcia

Active Member
Licensed User
Longtime User
Code sample:
Private Sub Demo
    Dim m1 As Map
    Dim indx As Int
  
    m1.Initialize
    indx = 1
    m1.Put(indx, "roer")
    indx = 900
    m1.Put(indx, "roer 900")
    m1.Put("alfa", "romeo")
  
    For Each v As Object In m1.Keys
        Log(v)
        If v Is String Then Log("string")
        If v Is Int Then Log("int")
    Next
  
    File.WriteMap(File.DirData("appname"), "file1.map", m1)
  
    m1.Initialize
    m1 = File.ReadMap(File.DirData("appname"), "file1.map")
    Log("Load data") 
    For Each v As Object In m1.Keys
        Log(v)
        If v Is String Then Log("string")
        If v Is Int Then Log("int")
    Next
  
    indx = 900
    Log("Search for 900 as int =" & m1.ContainsKey(indx))
    Log("Search for 900 forced as string =" & m1.ContainsKey(indx & ""))
  
End Sub

The file written with file.writemap

writemap:
#Fri May 15 09:14:00 CDT 2020
1=roer
900=roer 900
alfa=romeo

The log content

writemap:
1
int
900
int
alfa
string
Load data
1
string
900
string
alfa
string
Search for 900 as int =false
Search for 900 forced as string =true

Once this is understood I can manage it to solve my work. But, is this the expected mode of operation with write map - read map?
 

DonManfred

Expert
Licensed User
Longtime User
But, is this the expected mode of operation with write map - read map?
Method_636.png
File. WriteMap (Dir As String, FileName As String, Map As Map)

Creates a new file and writes the given map. Each key value pair is written as a single line.
All values are converted to strings.

The answer is YES.

If you want to write and read back the map correctly then your should use
B4X:
    Dim m As Map = CreateMap("January": 1, "February": 2)
    
    Dim b4xser As B4XSerializator
    ' get the bytes and do whatever you want with
    Dim bytes() As Byte = b4xser.ConvertObjectToBytes(m)
    ' Or just just RAF to store it to a file
    Dim raf As RandomAccessFile
    raf.Initialize(File.DirInternal,"mapobject",False)
    raf.WriteB4XObject(m,0)

    Dim raf As RandomAccessFile
    raf.Initialize(File.DirInternal,"mapobject",False)
    Dim m As Map = raf.ReadB4XObject(0)
 
Upvote 0

roerGarcia

Active Member
Licensed User
Longtime User
In any case, I will change the keys to string throughout the process.

The alternate mode you suggest I will save for another occasion. Thank you.

Sorry, I should have checked the documentation first, even if I came to that conclusion after two or three tests.
 
Upvote 0
Top