Take the 2-minute tour ×

I am trying to programmatically add a Fragment to a ScrollView that has a LinearLayout. For some reason, when I call the following function, it doesn't appear to add any element to the LinearLayout.

Here is the code: When the user clicks a button the following code is called that is supposed to add the fragment to the LinearLayout

public void refresh(View v) {
    CourseManagement cm = CourseManagement.getInstance();
    ArrayList<Course> courses = cm.getCourses();
    if(courses.size()>0) {
        Iterator<Course> it = courses.iterator();
        while(it.hasNext()) {
            Course c = it.next();
    } else {
        //No Classes In List;

This function calls the following function for every class in the arraylist:

private void addCourse(Course c) {
    LinearLayout destination = (LinearLayout) findViewById(R.id.addListCourses);
    FrameLayout fl = new FrameLayout(this);
    CreateFragTests frag = new CreateFragTests();
    fl.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.add(fl.getId(), frag).commit();

The Fragment itself is here:

public class CreateFragTests extends Fragment {

private static int uniqID = 0;
private static String uniqPrefix = "courseList";
private Course course;

public CreateFragTests() {

    //After some debugging, I have found that container is passed as null to this
    //this function which may be part of the problem?
    return inflater.inflate(R.layout.activity_create_frag_tests, container, true);

public void setCourse(Course c) {
    this.course = c;
    setInstructorsName(course.instructorLastName+", "+course.instructorFirstName);

public String getUniqID() {
    return uniqPrefix+"_"+uniqID;

After some debugging, I have found that when the onCreateView() is called, it receivies a null value for container. I have modeled my code after the examples given here: How do I add a Fragment to an Activity with a programmatically created content view and here: http://developer.android.com/training/basics/fragments/fragment-ui.html

EDIT: Also if I use this same code but try adding a textview instead of a fragment it works just fine.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

The problem lies here fl.setId(frag.getId()); . Instead of passing frag.getId() as its id, you should pass a unique id into it.

There are 2 ways you can do, either define the id in XML or in the class For example

private static final int CONTAINER_ID = 123456;

And use it to set the FrameLayout id.


or a simpler approach will be as follow

private void addCourse(Course c) {
    CreateFragTests frag = new CreateFragTests();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.add(R.id.addListCourses, frag).commit();
share|improve this answer

Your Answer


