Search code examples
androidlistviewcustom-adapter

ListView Android - displays two Items from the List < String>


I'm trying to do ListView. This is my code:

List<String> list = new ArrayList<>();
String[] add1 = {"FirstName1 ","LastName1", "12-12.1993"};
String[] add2 = {"FirstName2 ","LastName2", "20-12.1993"};
// Then adds these tables to the list;
list.add(add1[0] + add1[1] + add1[2]);
list.add(add2[0] + add2[1] + add2[2]);
//I create a ListView adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_2, list);

Now, My ListView looks like this: "FirstName1 LastName1 12-12.1993" etc.

I would like to looks like this: "FirstName1 LastName1".

I could not deleted the date, because it need to be sent to SecondActivity.


Solution

  • Make new Class that hold a Person

    Person.java

    public class Person {
        private String name;
        private String surname;
        private String date;
    
    
        public Person(String name, String surname, String date) {
            this.name = name;
            this.surname = surname;
            this.date = date;
        }
    
    
       public String getName() {
            return name;
        }
    
        public String getSurname() {
            return surname;
        }
    
        public String getDate() {
            return date;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", surname='" + surname + '\'' +
                    ", date='" + date + '\'' +
                    '}';
        }
    }
    

    Then on your main activity create an ArrayList. this Array holds a list of Persons

       ArrayList<Person> list =new ArrayList<>();
       list.add(new Person("FirstName1 ","LastName1", "12-12.1993"));
       list.add(new Person("FirstName2 ","LastName2", "20-12.1993"));
    

    if you want to see the items in ArrayList you can type this:

    list.get(0).toString();
    

    or

    Log.e("ArrayList","ArrayList Position 0 :"+list.get(0).toString());
    

    or Get the name of user at position 0

    Log.e("ArrayList","Name Position 0 :"+list.get(0).getName());
    

    Finally you must Create a Custom Adapter that you pass him the Custom Array.

    CustomAdapter adapter= new CustomAdapter(this,list);
    

    just look this tutorial it will help : Tutorial