2017-03-11 22 views
0

클래스를 사용하는 arraylist의 정보를 추가하고 목록보기의 배열 어댑터에 정보를 추가하는 방법을 알아 내려는 데 문제가 있습니다. 이 배열에서 이름을 추가하려고합니다.배열 어댑터에 클래스를 사용하여 arraylist 추가

어떻게 할 수 있습니까?

public class PersonClass { 

final private String firstName; 
final private String lastName; 
final private String birthday; 
final private int personPic; 

private PersonClass(String fName, String lName, String bDay, int pic) { 

    firstName = fName; 
    lastName = lName; 
    birthday = bDay; 
    personPic = pic; 

} 

public String toString() { 
    return firstName+" "+lastName+" "+birthday+" "+personPic; 
} 

public static void main(String args[]){ 

    // Information for each person using the PersonClass 
    PersonClass person1 = new PersonClass("first name", "last name", "01/01/2000", R.drawable.pic1); 
    // ..... up to 10... 


    // ArrayList 
    final ArrayList<PersonClass> personList = new ArrayList<>(); 

    // Add person data to array list 
    personList.add(person1); 
    personList.add(person2); 
    personList.add(person3); 
    personList.add(person4); 
    personList.add(person5); 
    personList.add(person6); 
    personList.add(person7); 
    personList.add(person8); 
    personList.add(person9); 
    personList.add(person10); 

    } 

} 

이 내 배열 어댑터입니다 :

나는이 별도의 클래스 (있으며, toString이 정확한지 확인되지 않음)를 가지고있다.

배열에 정보를 추가하는 클래스가 있기 때문에 어댑터에 arraylist 이름을 추가 할 수 없습니다. 그러나 목록보기에서 배열의 이름을 표시하기 만하면됩니다.

+0

당신이 더 당신이 달성하고자하는 것을 설명 할 수 주요? – cody123

+0

일부 정보가있는 사람을 배열 목록에 추가하고 있습니다. 이 목록에서 이름을 가져 와서 목록보기에 추가해야합니다. 어댑터 코드가 있습니다 : ArrayAdapter arrayAd = new ArrayAdapter (this, android.R.layout.simple_list_item_1, ???); ... 그러나 이것은 내가가는 한 무엇을 해야할지 잘 모르겠습니다. – art3mis

+0

내 답변을 올렸습니다. 같은 것을 찾으신다면 알려주십시오. – cody123

답변

1
import java.util.ArrayList; 
import java.util.List; 

class Person { 
    private String firstName; 

    //Might be more fields 

    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    public Person(String firstName) { 
     super(); 
     this.firstName = firstName; 
    } 

} 

public class SO1 { 

    public static void main(String[] args) { 

     List<Person> personList = new ArrayList<Person>(); 
     //Either you can directly add first name in adaptor 
     for (int i = 0; i < 10; i++) { 
      personList.add(new Person("Name "+i)); 
     } 

     //If you have list than you have to iterate it and add first name 
     List<String> adaptorList = new ArrayList<String>(); 
     personList.forEach(p -> adaptorList.add(p.getFirstName())); 

     System.out.println(adaptorList); 
    } 

} 
+0

이것은 완벽했습니다. 그게 내가 끈을 잡는 데 필요한거야. 고맙습니다. – art3mis

1

이름에 대한 getter를 작성하십시오. 멤버 변수는 소위 getter 및 setter 메서드로 액세스하기 위해 private입니다. 따라서 PersonClass에 getFirstName() 메서드가 필요합니다. 에서

public String getFirstName() 
{ 
return firstName; 
} 

당신의

List<String> nameList = new ArrayList<>(); 

nameList.add(person1.getFirstName()); 
관련 문제