Android - why is this telling me "Content view not yet created"?
Asked Answered
I

3

20

This is a populating a listview on a fragment from a database:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {

            LinearLayout Layout5 = (LinearLayout) inflater.inflate(R.layout.tab_frag5_layout, container, false);

            Cursor allBands;
            MyDatabase db;

            Context ctx = (Context)TabFragment5.this.getActivity();


            db = new MyDatabase(ctx);
            allBands = db.getBands();


            ListAdapter adapter = new SimpleCursorAdapter (ctx, 
                    R.layout.listelement, 
                    allBands, 
                    new String[] {"BandName"},  
                    new int[] {R.id.text15});

            getListView().setAdapter(adapter);  

            return Layout5;

         }

Why is this giving me the "Content view not yet created" On logcat? the program forces close when the fragment opens...

Ilk answered 15/2, 2012 at 0:42 Comment(2)
Shouldn't be first statement setContentView(..)?Eijkman
I don't think so, I'm working with fragments.Ilk
I
56

I solved it by moving the adapter and the getListview to onActivityCreated(...).

onCreateView just inflates and returns the layout.

Ilk answered 15/2, 2012 at 22:6 Comment(3)
When you call setAdapter(), the ListFragment checks to ensure there is a list defined in your layouts and since onCreateView() hasn't given the fragment its view, it's a chicken and egg problem.Chas
Do both setAdapter() and getListView() the ensure checking? I'm sure about getListView(), but not about setAdapter()Implore
why not onViewCreated. it seems to be the most intuitive option.Trinitrobenzene
T
2

A Fragment should usually put inside an Activity while the onCreateView() will contribute the layout of Fragment to its container Activity.

Quoted from http://developer.android.com/guide/topics/fundamentals/fragments.html

A fragment is usually used as part of an activity's user interface and contributes its own layout to the activity.

So, the problem may probably be caused by the missing of setContentView() in your container Activity instead of your Fragment.

Tillfourd answered 15/2, 2012 at 1:48 Comment(1)
Please read the folloup to this question: #9297651Ilk
A
1

I had the same issue but my fault was to call a (invisible) fragment from a background task via an interface. so the invisible fragment tried to use its view which was not available... i fixed it with the same solution: the interface function checks if fragment isVisible(). Thank you for showing me the right direction...

 public void updateListInterface(){
    if(this.isVisible()) {
        this.initListAdapter();
        getLoaderManager().restartLoader(0, null, this);
    } else {
        Log.v(TAG, "view is not visible");
    }
}
Auriculate answered 12/8, 2015 at 16:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.