SpannableStringBuilder not display image span for every data from Firebase (Kotlin)

I retrieve the data from FireBase and trying to display an image next to each data (TextView). But the image is displayed on the first data only.

This is the output:

enter image description here

I want every data to have an image.

Here is my code:

val database = FirebaseDatabase.getInstance().reference

val getData = object : ValueEventListener {
     override fun onDataChange(snapshot: DataSnapshot) {
     
          val myData = SpannableStringBuilder()

          for (i in snapshot.children) {
               val data = i.child("myData").value

               myData.append("$datann")
               
               // Get image from drawable and set size
               val drawable: Drawable? = context?.let { ContextCompat.getDrawable(it, R.drawable.myImage) }
               drawable?.setBounds(0, 0, textView.lineHeight, textView.lineHeight)
               
               // Set image span to the first letter
               val span: ImageSpan? = drawable?.let { ImageSpan(it, ImageSpan.ALIGN_BASELINE) }
               myData.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
          }

          textView.text = myData
     }

     override fun onCancelled(error: DatabaseError) {

     }
}

database.addValueEventListener(getData)

Answer

The problem is at myData.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE). You always set the image span at the first of the whole string. Do something like this:

override fun onDataChange(snapshot: DataSnapshot) {

    val builder = SpannableStringBuilder()

    snapshot.children.forEach { data ->
        builder.append("$data#") // the `#` doesn't mind and will be replaced with the image span

        val span = context?.let {
            ImageSpan(it, R.drawable.myImage, DynamicDrawableSpan.ALIGN_BASELINE)
        }

        builder.setSpan(
            span,
            builder.length - 1,
            builder.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        builder.append("nn") // at the end, append new lines
    }
    
    textView.text = builder
}