java - Passing one type of data to different places (retrofit) -
i'm new retrofit , have question. want create 1 call server , use downloaded data in different places in app. i'm using viewpager few fragments , each fragment need same data dataresponse class create different views. best way , how like? how retrofit class like. in advance!
public class apiclientfactory { public static final string baseurl = "https://earthquake.usgs.gov/fdsnws/event/1/"; public apiclient createapiclient(){ retrofit retrofit = new retrofit.builder() .baseurl(baseurl) .addconverterfactory(gsonconverterfactory.create()) .build(); return retrofit.create(apiclient.class); } } public interface apiclient { @get("query") call<dataresponse> getdata(@querymap map<string, string> options); }
i assume have activity contains viewpager. in activity's oncreate() method can make request. when receive response can build adapter (fragmentpageradapter) , pass dataresponse there. in adapter build fragments , set arguments dataresponse.
the sample code:
public class youractivity extends appcompatactivity { private fragmentpageradapter madapter; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); ...// makerequest(); //implement method data } //when response received call method private void onresponse(dataresponse response) { //create adapter madapter = new custompageradapter(response, getsupportfragmentmanager()); //don't forget set adapter viewpager } static class custompageradapter extends fragmentpageradapter { dataresponse mresponse; custompageradapter(dataresponse response, fragmentmanager fm) { super(fm); mresponse = response; } @override public fragment getitem(int position) { //create fragments , set arguments return customfragment.instance(mresponse); } @override public int getcount() { return 1; //number of fragments } } } public class customfragment extends fragment { private static final string key_response = "key_response"; public static customfragment instance(dataresponse response) { bundle args = new bundle(); args.putparcelable(key_response, response); customfragment f = new customfragment(); f.setarguments(args); return f; } @override public void onviewcreated(view root, bundle savedinstancestate) { super.onviewcreated(root, savedinstancestate); dataresponse response = getarguments().getparcelable(key_response); //do response whatever want } }
make sure dataresponse implements parcelable interface.
Comments
Post a Comment