Print the contents of a Bundle to Logcat?

后端 未结 10 648
孤独总比滥情好
孤独总比滥情好 2020-12-24 04:47

Is there an easy way to print the contents of a Bundle to Logcat if you can\'t remember the names of all the keys (even being able to print just the key names w

10条回答
  •  温柔的废话
    2020-12-24 05:22

    Solution in Kotlin:

    fun Bundle.toPrintableString(): String {
        val sb = StringBuilder("{")
        var isFirst = true
        for (key in keySet()) {
            if (!isFirst)
                sb.append(',')
            else
                isFirst = false
            when (val value = get(key)) {
                is Bundle -> sb.append(key).append(':').append(value.toPrintableString())
                else -> sb.append(key).append(':').append(value)
                //TODO handle special cases if you wish
            }
        }
        sb.append('}')
        return sb.toString()
    }
    

    Sample:

        val bundle = Bundle()
        bundle.putString("asd", "qwe")
        bundle.putInt("zxc", 123)
        Log.d("AppLog", "bundle:${bundle.toPrintableString()}")
    

    Note that it doesn't handle all possible types of values. You should decide which are important to show and in which way.

提交回复
热议问题