setUserVisibleHint called before onCreateView in Fragment

Amit Yadav picture Amit Yadav · Jun 11, 2014 · Viewed 49.6k times · Source

I am working on ViewPager and using Fragment there I found

setUserVisibleHint() called before onCreateView() in Fragment

I am using Fragment from support library android.support.v4.app.Fragment

Is this is a problem with Library ?

How can I get rid of it ?

EDIT

I Override setUserVisibleHint() and not calling super to get rid of it.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    //FIXED: setUserVisibleHint() called before onCreateView() in Fragment causes NullPointerException
    //super.setUserVisibleHint(isVisibleToUser);
}

Answer

vikoo picture vikoo · Jul 24, 2014
// create boolean for fetching data
private boolean isViewShown = false;

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (getView() != null) {
        isViewShown = true;
        // fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
        fetchData();
    } else {
        isViewShown = false;
    }
} 

Use isViewShown instance variable to decide whether to fetch data in onCreateView() or in setUserVisibleHint().

Below code contains logic for onCreateView():

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.main_layout, container, false);

   // view initialization steps.......

   if (!isViewShown) {
        fetchData();
   } 
   // do other stuff
}

This code will solve your problem. As It solved my problem. :)

This trick will fetch data in onCreateView() for direct jumping from one page to another, whereas when you swipe the view it will fetch the data from setUserVisibleHint() method. :)