I can see that the log.d requires
Log.d(String TAG, String).
How do I print to the android debug logcat a List String instead of just a String?
You need to implement toString() method for your custom type to get expected output. List<Dog> dogList = new ArrayList<Dog>(); Now, if you want to print this List in LogCat properly then you need to implement toString() method in Dog class. Now, you will get proper result if you call list.
If you want to print a list of integers, you can use a map() function to transform them into strings. Then you can use the join() method to merge them into one string and print them out. This particular example works such that the map() function creates a new list that contains each integer as a string.
We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.
Make use of toString() method which is available for most common data structures:
Log.d("list", list.toString());
Above statement will give you the expected result if you declare your List
/Collection
using Generic type defined in Java. Such as String, Integer, Long etc. Cause, they all have implemented toString()
method.
Custome Generic Type:
But if you declare the List
using your own custom type then you will not get proper output by just calling list.toString()
. You need to implement toString()
method for your custom type to get expected output.
For example:
You have a model class named Dog
as below
public class Dog{
String breed;
int ageC
String color;
}
You declared a List
using Dog
type
List<Dog> dogList = new ArrayList<Dog>();
Now, if you want to print this List in LogCat
properly then you need to implement toString()
method in Dog
class.
public class Dog{
String breed;
int age
String color;
String toString(){
return "Breed : " + breed + "\nAge : " + age + "\nColor : " + color;
}
}
Now, you will get proper result if you call list.toString()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With