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
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.
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) + "\"");
}
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:
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.Java 8 stream one liner:
bundle.keySet().stream().forEach(k -> Log.d(TAG, k + " = " + bundle.get(k)));