Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getView() returns null

I basicall have an AsyncTask (run from main Activity) that populates a ViewPager inside a fragment. I'm inflating an xml layout file to populate the ViewPager.

The problem is that I can't get pointers to the views inside the layout (imageview, textview) so that I can change then at runtime. I know it's probably because getView() returns null. I've read that it's probably because onCreateView() hasn't been called, yet. Anybody know what I can do to solve this?


My code's a bit of a mess right now.

Here's a simpler explanation to what I'm doing:

  1. MainActivity Asynctask populates a database and sends pointer to Fragment. Something like SendToFragement(db);
  2. The Fragment method ReceiveFromActivity(db) receives db pointer and populates the ViewPager.

It works fine if I'm just creating TextViews, setting text, and adding TextViews to the Viewpager. But, of course, I want to make it look better so I've inflated an xml layout. The problem is that I can't change the contents of the xml layout because getView() is returning NULL so getView().findViewById() doesn't work.

like image 732
user1923613 Avatar asked Feb 28 '13 13:02

user1923613


Video Answer


1 Answers

Depending on the implementation of your PagerAdapter, it is possible that a Fragment no longer in view will have their View destroyed in order to free up resources. As such, there's no need to update the View because it will be created again in onCreateView() with the updated information. getView() will return a view in between calls to onCreateView() and onDestroyView(). Outside of that, the Fragment can still exist in memory, but not attached to any View, thus getView() will return null.

So basically,

View fragmentView = getView();
if(fragmentView != null) {
  // we are in view or at least exist. Update the elements.
}
// Else don't worry about it. Just update the data.
like image 59
DeeV Avatar answered Oct 16 '22 18:10

DeeV