Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a List<String> to logcat

Tags:

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?

like image 835
johnsonjp34 Avatar asked Mar 13 '14 17:03

johnsonjp34


People also ask

How to print list of string in Logger java?

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.

How do I print an integer 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.

How do I convert a list to a string in Java?

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.


1 Answers

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().

like image 133
Hamid Shatu Avatar answered Sep 23 '22 20:09

Hamid Shatu