Search code examples
javaandroidparent-childillegalstateexception

Adding multiple TextViews into LinearLayout dynamically


I have a problem with adding TextViews dynamically. I want to add hired rooms from list by method getRoomList() at first, and after that add rooms with text ": Free", which are in the existingRoomNames array but are not hired.

public void checkRoomsAndDate() {
    linearLayout = (LinearLayout) findViewById(R.id.linear1);
    linearLayout.removeAllViews();
    for (Room room : mCalendarModel.mList.getRoomList()) {
        addHiredRoomToLayout(room);
    }
    addNotHiredRoomsToLayout();
}

public void addHiredRoomToLayout(Room room) {
    textView = new TextView(this);
    textView.setText(room.getParameters());
    linearLayout.addView(textView);
}

public void addNotHiredRoomsToLayout() {
    textView2 = new TextView(this);
    for (String name : Constants.existingRoomNames) {
        boolean contains = false;
        for (Room room : mCalendarModel.mList.getRoomList()) {
            if (room.getName().equals(name)) {
                contains = true;
            }
        }
        if (!contains) {
            textView2.setText(name + ": Free");
            linearLayout.addView(textView2);
        }
    }
}

Here's the XML:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="313dp"
    android:layout_height="150dp"
    android:id="@+id/linear1"
    android:layout_gravity="center"></LinearLayout>

which is inside the parent LinearLayout.

I get exception like this:

`java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.`

on the last line:

linearLayout.addView(textView2);

What's the problem there?


Solution

  • You are adding the same view to the layout again. Change your function to

    public void addNotHiredRoomsToLayout() {
    
    for (String name : Constants.existingRoomNames) {
        textView2 = new TextView(this);
        boolean contains = false;
        for (Room room : mCalendarModel.mList.getRoomList()) {
            if (room.getName().equals(name)) {
                contains = true;
            }
        }
        if (!contains) {
            textView2.setText(name + ": Free");
            linearLayout.addView(textView2);
        }
    }
    }