android - How do I prevent viewpager from making network request, if the network request has already been made for all the pages -
i have viewpager 3 pages uses fragmentstatepageradapter. fragment each page same data changes depending on position of page. inflation logic each item on page defined in fragment's oncreateview, , thats why each time new instance of fragment inflated network calls repeated though have been made on previous visit page.
my question how prevent this. new android , know missing here, if approach wrong please point out how should prevent behavior.
some code : inside activity's oncreate
viewpager mviewpager = (viewpager) findviewbyid(r.id.vpbooks); pageradapter mpageradapter = new bookspageadapter(getsupportfragmentmanager(), mainactivity.this, extras); mviewpager.setadapter(mpageradapter);
inside viewpageradapter
public bookspageadapter(fragmentmanager fm, context context, bundle extras) { super(fm); this.extras = extras; this.cls = extras.getstringarray("cls"); this.context = context; } @override public fragment getitem(int position) { return bookspagefrag.newinstance(extras, cls[position]); } @override public int getcount() { return cls.length; }
inside fragment :
@override public void oncreateview(bundle savedinstancestate) { super.oncreate(savedinstancestate); url = getarguments().getstring("url"); urlfare = getarguments().getstring("fare"); log.d("url sapf", url); queue = volley.newrequestqueue(this.getactivity()); getbooks();// here network calls made }
so want if fragement particular cls[position] instantiated , data fetched on revisiting same position should not make new network calls
you need use parcelable . think using list array of class object .follow following steps
1.) implement parcelable in class object
2.)in onsavedinstancestate use following code
@override public void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putparcelablearraylist("key", mlistparcel); }`
3.) in oncreate method use code
@override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { super.oncreateview(inflater, container, savedinstancestate); /*set recyclerview stuff here*/ if(savedinstancestate!=null) { //fragment has been loaded earlier\ marraylist=savedinstancestate.getparcelablearraylist("key"); //use list here } else { //fragment new // make request here } }
Comments
Post a Comment