Android Question Cleaning Out Map Null Values Help???

Mashiane

Expert
Licensed User
Longtime User
Hi

I have a piece of code that I want to use to clean out all map values that are null to be empty strings.
As much as the map variable is passed and has values, the following piece of code always crashes where KeyList is assigned to xMap.Keys with a cannot be cast error.

My logs shows the map variable well enough

B4X:
Sub CleanMapNull(xMap As Map)
   Private KeysList As List
   Private key As String
   Private mVal As Object
   Private i As Int
   Log(xMap)
  
   KeysList.Initialize
   KeysList = xMap.Keys
  
   For i= 0 To KeysList.Size - 1
       key = KeysList.Get(i)
    mVal = xMap.Get(key)
    If mVal = "null" Then xMap.Put(key, "")
   Next
   
End Sub

Can someone please advise? Thanks
 

Mashiane

Expert
Licensed User
Longtime User
Try this:
B4X:
Sub CleanMapNull(xMap As Map) As Map
     For Each k As String In xMap.Keys
         If xMap.Get(k) = "null" Or xMap.Get(k) = Null Then xMap.Put(k,"")
   Next
    Return xMap
End Sub

You can't do KeysList = xMap.Keys, because xmap.keys is not a simple list, it is an iterableList
Thanks, strange enough, I think I once used similar code and it worked or I hoped it was working


B4X:
'Description: Sort a map by its keys in ascending order
'Tag: map, sort, asc
Sub SortMapKeys (m As Map, SortAsc As Boolean)
   Private KeysList As List
   Private m2 As Map
   Private key As String
   Private mVal As Object
   Private i As Int
   KeysList.Initialize
   m2.Initialize
 
   ' get all the keys
   KeysList = m.Keys
   KeysList.Sort(True)
 
   For i= 0 To KeysList.Size - 1
       key = KeysList.Get(i)
    mVal = m.Get(key)
    m2.Put(key, mVal)
   Next
  m.Clear
  For Each m2Key As String In m2.Keys
      m.Put(m2Key, m2.Get(m2Key))
  Next
End Sub
 
Upvote 0
Top