Convert Map to Bundle in android

前端 未结 7 2089
面向向阳花
面向向阳花 2020-12-29 17:58

Is there an easy way to convert a Map to a Bundle in android without explicit iteration?

Why?

Firebase returns a Map for Notification

相关标签:
7条回答
  • 2020-12-29 18:29

    Came across this same issue with firebase messaging and created a kotlin extension function for it. The gist is here, code below. Although I am using this method there are some caveats:

    • it doesn't cover all of the types that can be put into a bundle
    • it is still under development and hasn't been fully tested

    With this in mind, please use it as a guide not a definitive solution. I will keep the gist up to date as it evolves.

    import android.os.Bundle 
    import android.os.IBinder
    import android.os.Parcelable
    import java.io.Serializable
    
    fun <V> Map<String, V>.toBundle(bundle: Bundle = Bundle()): Bundle = bundle.apply {
      forEach {
        val k = it.key
        val v = it.value
        when (v) {
          is IBinder -> putBinder(k, v)
          is Bundle -> putBundle(k, v)
          is Byte -> putByte(k, v)
          is ByteArray -> putByteArray(k, v)
          is Char -> putChar(k, v)
          is CharArray -> putCharArray(k, v)
          is CharSequence -> putCharSequence(k, v)
          is Float -> putFloat(k, v)
          is FloatArray -> putFloatArray(k, v)
          is Parcelable -> putParcelable(k, v)
          is Serializable -> putSerializable(k, v)
          is Short -> putShort(k, v)
          is ShortArray -> putShortArray(k, v)
    
    //      is Size -> putSize(k, v) //api 21
    //      is SizeF -> putSizeF(k, v) //api 21
    
          else -> throw IllegalArgumentException("$v is of a type that is not currently supported")
    //      is Array<*> -> TODO()
    //      is List<*> -> TODO()
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-29 18:30

    I guess a good old fashioned for loop is the easiest way:

        Bundle bundle = new Bundle();
        for (Map.Entry<String, String> entry : getData().entrySet()) {
            bundle.putString(entry.getKey(), entry.getValue());
        }
    
    0 讨论(0)
  • 2020-12-29 18:32

    Nowadays you can use fun bundleOf(vararg pairs: Pair<String, Any?>)

    0 讨论(0)
  • 2020-12-29 18:41

    Neat Kotlin solution using spread operator will look like that:

    fun Map<String, Any?>.toBundle(): Bundle = bundleOf(*this.toList().toTypedArray())
    
    0 讨论(0)
  • 2020-12-29 18:50
     private ArrayList<Bundle> convertMapToBundleList(ArrayList<HashMap<String, String>> mapList)
    
    0 讨论(0)
  • 2020-12-29 18:51

    here is how I did it in Kotlin

    val bundle = Bundle()
    
    for (entry in data.entries)
        bundle.putString(entry.key, entry.value)
    
    0 讨论(0)
提交回复
热议问题