Print the contents of a Bundle to Logcat?

后端 未结 10 609
孤独总比滥情好
孤独总比滥情好 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.

    0 讨论(0)
  • 2020-12-24 05:23

    You can get more specific by printing the mapped value as follows:

    for (String key : bundle.keySet())
    {
        Log.d("Bundle Debug", key + " = \"" + bundle.get(key) + "\"");
    }
    
    0 讨论(0)
  • 2020-12-24 05:27

    Bundle#keySet() should work.

    for (String key: bundle.keySet())
    {
      Log.d ("myApplication", key + " is a key in the bundle");
    }
    

    And if you want to get the Object, you can use Bundle#get(String key)(which is also in the same documentation I linked at the top of my answer). However, keep in mind using the generic get() call:

    • You're working with Object. If you're simply printing to a Log, toString() will be invoked and all will be fine. However, if you actually want to use the key's pair, you need to do instanceof checks to avoid calling the wrong method.
    • Since toString will be invoked, if you have a special Object (eg ArrayLists, or special Serializable/Parcelable extras) you're most likely not going to get anything useful from the printout.
    0 讨论(0)
  • 2020-12-24 05:27

    Java 8 stream one liner:

    bundle.keySet().stream().forEach(k -> Log.d(TAG, k + " = " + bundle.get(k)));
    
    0 讨论(0)
提交回复
热议问题