Print a List<String> to logcat
Asked Answered
C

3

22

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?

Catina answered 13/3, 2014 at 17:7 Comment(1)
I mean this as a serious question. Why don't you just read the docs for List and see what methods are available? you would have found toString(). It's quicker than creating a question here.Niobous
A
47

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

Adze answered 13/3, 2014 at 17:8 Comment(1)
For KOTLIN Use "data class".. It has toString() and all necessary methods.Damalis
B
0
if (list != null && list.size() > 0)
                {
                    for (int i = 0; i < list.size(); i++) {
                        mStrp = mStrp + list.get(i).getdataname() + "/";
                        mStrD  = mStrD + list.get(i).getdata2name() + "/";
                    }

                    //if you want to delete last "/"
                mStrp = mStrLatPick.substring(0,mStrLatPick.length() - 1);

                    value = mStrp + mStrD;
                    Log.d("value",value);
                }
Baltazar answered 11/10, 2019 at 8:57 Comment(0)
C
0

If you want to print the Array List element on the console.and also add , remove an element.

    ArrayList myFavAnimal = new ArrayList();

    myFavAnimal.add("Lion");
    myFavAnimal.add("Tiger");
    myFavAnimal.add("Leopard");
    Log.i("MyTag",myFavAnimal.get(0) +"");
    myFavAnimal.remove(1);
    Log.i("MyTag",myFavAnimal.toString());
    myFavAnimal.remove("Lion");
    Log.i("MyTag",myFavAnimal.toString());
Carlisle answered 20/5, 2020 at 2:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.