Android Question how to get a List from Map after write and read the map.

Hadi57

Member
Probably a beginner problem. but i can't get a list in map after Write it and Read again. i get this error message:
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List


B4X:
    Dim mapSetting As Map
    mapSetting.Initialize
    Dim List1 As List
    List1.Initialize2(Array As String("Name1", "Name2", "Name3"))
    mapSetting.Put("MyList", List1)
    File.WriteMap(File.DirInternal, "Setting.txt", mapSetting)
    
    mapSetting = File.ReadMap(File.DirInternal, "Setting.txt")
    Dim List2 As List = mapSetting.Get("MyList")
    For Each s As String In List2
        Log(s)
    Next
 

Brian Dean

Well-Known Member
Licensed User
Longtime User
File.WriteMap (and File .WriteList) convert all variables to strings and produce a text file. This means that they cannot save objects (like Lists) within Lists. You could use
KeyValueStore class instead (or RandomAccessFile.WriteObject).
 
Upvote 0

Hadi57

Member
File.WriteMap (and File .WriteList) convert all variables to strings and produce a text file. This means that they cannot save objects (like Lists) within Lists. You could use
KeyValueStore class instead (or RandomAccessFile.WriteObject).
Thank you 'Brian Dean', your help saved me :)
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
i can't get a list in map after Write it and Read again
Another option to KVS or RAF is to use json:
1. Put your list in your map like you have
2. then, JSONGenerator.Initialize(mapSetting)
3. Save json string to a file:
B4X:
File.WriteString(File.DirInternal,"Setting.json",  JSONGenerator.ToPrettyString(2))
4. Retrieve the file and parse the json string to get the list items:
B4X:
Dim s As String =File.ReadString(File.DirInternal,"Setting.json")
 
Upvote 0
Top