My question is how to print print the value of arraylist contents in my logcat? Each array has two string.. Do I have to change it to array first?
The following is my school class:
public class SCHOOL {
private String schoolid;
private String schoolname;
private List<STUDENT> students = new ArrayList<>();
// getters and setters for schoolid, schoolname
public String getSchoolid() {
return schoolid;
}
public void setSchoolid(String schoolid) {
this.schoolid = schoolid;
}
public String getSchoolname() {
return schoolname;
}
public void setSchoolname(String schoolname) {
this.schoolname = schoolname;
}
public void setStudents(List<STUDENT> students) {
this.students = students;
}
public List<STUDENT> getStudents() {return this.students;}
public void addStudent(String names, String age) {
STUDENT student = new STUDENT();
student.setNames(names);
student.setAge(age);
students.add(student);
}
The following is my student class: public class STUDENT {
private String names;
private String age;
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
The following is my main activity:
...
SCHOOL school = new SCHOOL();
school.addStudent("kent", "43");
school.addStudent("Winnie", "42");
school.addStudent("Dennis", "41");
List<STUDENT> studentsList = school.getStudents();
Log.d(tag, String.valueOf(studentsList));
...
The result is as followed:
Tag Activity: [com.example.spidey.jsontosql.STUDENT@5286b6d8,
com.example.spidey.jsontosql.STUDENT@5286b768,
com.example.spidey.jsontosql.STUDENT@5286b7b0]
Override method toString()
in class STUDENT
. For instance:
public class STUDENT {
String names;
String age;
@Override
public String toString() {
return "STUDENT{" +
"names='" + names + '\'' +
", age='" + age + '\'' +
'}';
}
}
You can write a output method for customized output, like:
public String outputStudents(List<STUDENT> studentsList) {
StringBuilder sb = new StringBuilder();
foreach (STUDENT student: studentLIst) {
sb.append(student.names);
sb.append(",");
sb.append(student.age);
sb.append(";");
}
return sb;
}
And use the code below to call this function:
List<STUDENT> studentsList = school.getStudents();
Log.d(tag, outputStudents(studentsList));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.