Android Question List from B4J to B4A

arfprogramas

Member
Licensed User
Longtime User
Hello

I made a simple program in B4J to create a List with some Type in it. I saved the list in a file and puted on my B4A app.
When I try to open the list file using the same custom type, throws me an error: java.lang.ClassCastException: java.lang.String cannot be cast to com.testprogram.readlistxx$_abc

Isn't possible to do this?

I did something like this in B4J:
B4X:
Type ABC(P As String, X As Int, Y As Int, Z As Int)
Sub CreateList
    Dim XX As List
    XX.Initialize
    
    For I = 0 To 100
        XX.Add(CreateABC("xxxxxxxxx", I, I, I))
    Next
    
    File.WriteList(File.DirApp, "xx.inf", XX)   
End Sub

And B4A code:

B4X:
Dim XX As List = File.ReadList(File.DirAssets, "xx.inf")
    For Each item As ABC In XX
        
        'etc
    Next
 

Midimaster

Active Member
Licensed User
You cannot save a Custom Type in this way. Better use KeyValueStore class. But this creates a file that is not longer readable with an editor. So if you need to store the Custom Types in a txt-format, you need a sub to re-arrange text lines to your custom type.


B4X:
    Type ABC(P As String, X As Int, Y As Int, Z As Int)
    Dim xxx As List
...
    SaveABCList(xxx)
...
   xxx=LoadABCList()
...
Sub SaveABCList(locList As List)
    Dim textline As String, StringList As List
    For Each loc As ABC In locList
        textline= loc.P & "|" & loc.X & "|" & loc.Y & "|" & loc.Z
        StringList.Add(textline)
    Next
    File.WriteList(File.DirApp, "xx.inf", StringList)
End Sub

Sub LoadABCList() As List
    Dim Elements() As String
    Dim StringList As List = File.ReadList(File.DirAssets, "xx.inf")
    Dim ReturnList As List
    For Each textline As String In StringList
        Elements=  Regex.Split("\|", textline)
        Dim loc As ABC
        loc.Initialize
        loc.P=Elements(0)
        loc.X=Elements(1)
        loc.Y=Elements(2)
        loc.Z=Elements(3)
        ReturnList.Add(loc)
    Next
    Return ReturnList
End Sub
 
Last edited:
Upvote 0

arfprogramas

Member
Licensed User
Longtime User
I followed your tip and did this in B4J:

B4J App:
Dim serial As B4XSerializator
File.WriteBytes(File.DirApp, "listcpp.inf", serial.ConvertObjectToBytes(List1))

And this in B4A:
B4A App:
Dim serial As B4XSerializator
List1 = serial.ConvertBytesToObject(File.ReadBytes(File.DirAssets, "listcpp.inf"))

Initially the B4A app thrown me this error: Suppressed: java.lang.ClassNotFoundException: com.arfprogramas.arfloterias.b4xmainpage$_listitemcpp
I realized that happens because the Type was not declared in Main global/Process global. I fixeded and the code worked like a charm.

It's a very elegant solution and way more practice. Thanks Erel.

Simple question: I've always declared types wherein the activities they'll be useful. Is the best approach declare Types in Main activity? Or it matters only for B4X Serialization?
 
Upvote 0
Top