Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my onCreateView method being called twice?

While debugging another issue, I realized that the onCreateView method of one of my activities was being called twice. I'm new to programming and I don't fully understand how android calls these methods when the activity loads, but it doesn't seem right to me that it would be called twice. Eliminating most of my code, I still see my System.out message twice.

public class AddCourse extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_course);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new AddCourseFragment()).commit();
        }
    }

    public static class AddCourseFragment extends Fragment {

        View rootView;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.fragment_add_course,
                container, false);
                        System.out.println("I see this TWICE!!!!");
            return rootView;
        }       
    }
}

This is almost exactly like my main activity implementation, but that one doesn't go through onCreateView twice. Thoughts?

My activity_add_course xml was requested...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

     <fragment android:name="com.NsouthProductions.gradetrackerpro.AddCourse$AddCourseFragment"
         android:id="@+id/AddCourseFrag" 
         android:layout_width="match_parent"
         android:layout_height="match_parent" />
</LinearLayout>
like image 227
NSouth Avatar asked Apr 08 '14 02:04

NSouth


1 Answers

Looks like you're adding the fragment twice. If you declare it in the xml then you don't need to add it programmatically as well.

You can remove this from your Activity's onCreate():

if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new AddCourseFragment()).commit();
        }
like image 69
brwngrldev Avatar answered Sep 29 '22 11:09

brwngrldev