setUserVisibleHint with Fragments for android -
im using 3 fragments in viewpager adapter. loading data parse(parse.com) , displaying them in recycler views. following code causing app crash. understanding when mainactivity loads, first fragment ie, gets viewed user setuservisiblehint function gets called , in v.findviewbyid code causes null pointer exception since setcontentview hasnt/ may not been called. proof if add 1sec delay setuservisisblehint code works properly.
now want add server pull requests using parse, add data in list adapter , populate recyclerview after user views page so
1) should add code in setuservisisblehint , add 0.5secc delay gets executed after setcontentview called ensuring dont null pointer exception error or
2) there better way/ other functions can use achieve same?
public class newsfeed extends fragment { linearlayoutmanager mlayoutmanager; boolean _arelecturesloaded=false; view v; progressbar bar; public newsfeed() { // required empty public constructor } @override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) { // inflate layout fragment v=inflater.inflate(r.layout.fragment_news_feed, container, false); recyclerview mrecyclerview = (recyclerview)v.findviewbyid(r.id.recycler_view); mrecyclerview.sethasfixedsize(true); mlayoutmanager = new linearlayoutmanager(v.getcontext()); mrecyclerview.setlayoutmanager(mlayoutmanager); mystickyadapter madapter = new mystickyadapter(v.getcontext()); mrecyclerview.setadapter(madapter); // mrecyclerview.additemdecoration(new stickyrecyclerheadersdecoration(madapter)); return v; } @override public void setuservisiblehint(boolean isvisibletouser) { super.setuservisiblehint(isvisibletouser); if (isvisibletouser && !_arelecturesloaded ) { _arelecturesloaded = true; v.findviewbyid(r.id.asd).setvisibility(view.gone); } } }//closes fragment
im using library recycler view stickyheaderrecyclerview
i highly recommend avoiding adding delays if you're running on main thread. avoid npe, try moving findviewbyid(r.id.asd) oncreateview method after inflate view:
@override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) { // inflate layout fragment v=inflater.inflate(r.layout.fragment_news_feed, container, false); v.findviewbyid(r.id.asd).setvisibility(view.gone);
this assuming r.id.asd in r.layout.fragment_news_feed
this post provide insight: setuservisiblehint called before oncreateview in fragment
Comments
Post a Comment