Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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);
                }

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());
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top