Search code examples
androidkotlinmodelpojo

The titleList is displayed incorrectly..?


in logcat I'm getting

[Title 1 [6 Name 6, 7 Name 7], Title 2 [6 Name 6, 7 Name 7], Title 3 [6 Name 6, 7 Name 7]]

what I want is

[Title 1 [1 Name 1, 2 Name 2], Title 2 [3 Name 3, 4 Name 4, 5 Name 5], Title 3 [6 Name 6, 7 Name 7]]

    var list:MutableList<Data> = ArrayList();
    val titlelist:MutableList<TitleList> = ArrayList()

    list.add(Data("1","Name 1"));
    list.add(Data("2","Name 2"));

    titlelist.add(TitleList("Title 1",list))
    list.clear()


    list.add(Data("3","Name 3"));
    list.add(Data("4","Name 4"));
    list.add(Data("5","Name 5"));

    titlelist.add(TitleList("Title 2",list))
    list.clear()


    list.add(Data("6","Name 6"));
    list.add(Data("7","Name 7"));

    titlelist.add(TitleList("Title 3",list))


    Log.d("TITLE_LIST",titlelist.toString())

My Pojo Classes are

Data.java

private String id;
private String name;

public Data(String id, String name) {
    this.id = id;
    this.name = name;
}

TitleList.java

private String title;
private List<Data> dataList;

public TitleList(String title, List<Data> dataList) {
    this.title = title;
    this.dataList = dataList;
}

Solution

  • You need to change the line which adds item to title list. In the constructor of TitleList, pass ArrayList(list) instead of list (Eg. titlelist.add(TitleList("Title 2",ArrayList(list)))). Do this for all 3 lines where you add items to title list. This is because if you use the variable list, this list is bound to the instance of title list you create and will change if you change the value of list. So the instance will always have the latest value you give to variable list. That is why you are always getting [6 Name 6, 7 Name 7] in all 3 cases.