How to load json data into fragment in android -


i want show 3 fragments in activity , load data json in fragments! want show each json data 1 fragment, in application load 3 fragments json datas in first enter application.
for example : when first enter application load of fragments datas, want load data when show fragment (swipe on fragment).
fragment 1 codes:

public class free_fragment extends fragment {      private recyclerview mrecyclerview;     private free_recycler_adapter madapter;     private recyclerview.layoutmanager mlayoutmanager;     private list<datamodel> datamodels = new arraylist<datamodel>();      private context context;      @override     public view oncreateview(layoutinflater inflater,                              viewgroup container, bundle savedinstancestate) {          view view = inflater.inflate(r.layout.fragment_free_layout, container, false);          context = getcontext();          loaddata();          ///----- recyclerview -----         mrecyclerview = (recyclerview) view.findviewbyid(r.id.pdf_recyclerview);         mrecyclerview.sethasfixedsize(true);         mrecyclerview.setlayoutmanager(new linearlayoutmanager(getactivity()));         madapter = new free_recycler_adapter(context, datamodels);         mrecyclerview.setadapter(madapter);           return view;     }      @subscribe     public void onevent(myevent event) {         list<datamodel> datamodels = event.getinfomodels();          if (event.fragmenttag.equals("forfragment1")) {             madapter.add(datamodels);             madapter.notifydatasetchanged();         }     }      private void loaddata() {         freedatainfo datainfo = new freedatainfo();         // here getmaindatainfo() should return server response         datainfo.getfreedatainfo(context);     }      @override     public void onresume() {         super.onresume();         eventbus.getdefault().register(this);     }      @override     public void onpause() {         eventbus.getdefault().unregister(this);         super.onpause();     } } 

fragment 1 asynctask codes:

public class freedatainfo {     private context mcontext;     private string serveraddress = freeserver_ip.getfreeip();      public void getfreedatainfo(context context) {         mcontext = context;         new getinfo().execute(serveraddress + "limit=10");     }      private class getinfo extends asynctask<string, void, string> {         eventbus bus = eventbus.getdefault();         private string ou_response;         private list<datamodel> infomodels = new arraylist<>();         private progressdialog dialog;          @override         protected void onpreexecute() {             //customprocessdialog.createandshow(mcontext);              dialog = new progressdialog(mcontext);             this.dialog.setmessage("شکیبا باشید...");             this.dialog.show();         }          @override         protected string doinbackground(string... params) {             okhttpclient client = new okhttpclient();              //string url = (string) params[0];             request request = new request.builder()                     .url(serveraddress + "limit=10")                     .cachecontrol(cachecontrol.force_network)                     .build();              response response;             try {                 response = client.newcall(request).execute();                 ou_response = response.body().string();                 response.body().close();                 if (ou_response != null) {                     try {                         jsonobject postobj = new jsonobject(ou_response);                         jsonarray postsarray = postobj.optjsonarray("result");                          (int = 0; <= postsarray.length(); i++) {                             jsonobject postobject = (jsonobject) postsarray.get(i);                              int id = postobject.getint("id");                             log.d("id", string.valueof(id));                             string title = postobject.getstring("title");                             string description = postobject.getstring("description");                             string image = postobject.getstring("image");                             string category = postobject.getstring("categoryname");                             string date = postobject.getstring("publishdate");                              log.d("data", "post id: " + id);                             log.d("data", "post title: " + title);                             log.d("data", "post image: " + image);                             log.d("data", "---------------------------------");                              //use title , id per requirement                             infomodels.add(new datamodel(id, title, description, category, date, image));                         }                     } catch (jsonexception e) {                         e.printstacktrace();                         log.e("error", string.valueof(e));                     }                 }             } catch (ioexception e) {                 e.printstacktrace();                 log.e("error2", string.valueof(e));             }             return ou_response;         }          @override         protected void onpostexecute(string result) {             //customprocessdialog.dissmis();              //stop progress             if (dialog.isshowing()) {                 dialog.dismiss();             }              if (result != null) {                 bus.post(new myevent("forfragment1", infomodels));             } else {                 toast.maketext(mcontext, "empty", toast.length_short).show();             }         }     } } 

fragment 2 codes:

public class paid_fragment extends fragment {      private recyclerview mrecyclerview;     private paid_recycler_adapter madapter;     private recyclerview.layoutmanager mlayoutmanager;     private list<datamodel> datamodels = new arraylist<datamodel>();      private context context;      @override     public view oncreateview(layoutinflater inflater,                              viewgroup container, bundle savedinstancestate) {          view view = inflater.inflate(r.layout.fragment_paid_layout, container, false);          context = getcontext();  /*        if (!eventbus.getdefault().isregistered(this)) {             eventbus.getdefault().register(this);         }*/          loaddata();          ///----- recyclerview -----         mrecyclerview = (recyclerview) view.findviewbyid(r.id.voice_recyclerview);         mrecyclerview.sethasfixedsize(true);         mrecyclerview.setlayoutmanager(new linearlayoutmanager(getactivity()));         madapter = new paid_recycler_adapter(context, datamodels);         mrecyclerview.setadapter(madapter);          return view;     }      @subscribe     public void onevent(myevent event) {         list<datamodel> datamodels = event.getinfomodels(); /*        if (datamodels.size() > 0) {             datamodels.remove(datamodels.size() - 1);             madapter.notifyitemremoved(datamodels.size());             //madapter.setloaded();         }*/         if (event.fragmenttag.equals("forfragment2")) {             madapter.add(datamodels);             madapter.notifydatasetchanged();         }     }      private void loaddata() {         paiddatainfo datainfo = new paiddatainfo();         // here getmaindatainfo() should return server response         datainfo.getpaiddatainfo(context);     }      @override     public void onresume() {         super.onresume();         eventbus.getdefault().register(this);     }      @override     public void onpause() {         eventbus.getdefault().unregister(this);         super.onpause();     } } 

fragment 2 asynctask codes:

public class paiddatainfo {     private context mcontext;     private string serveraddress = paidserver_ip.getpaidip();      public void getpaiddatainfo(context context) {         mcontext = context;         new getinfo().execute(serveraddress + "limit=10");     }      private class getinfo extends asynctask<string, void, string> {         eventbus bus = eventbus.getdefault();         private string ou_response;         private list<datamodel> infomodels = new arraylist<>();         private progressdialog dialog;          @override         protected void onpreexecute() {             //customprocessdialog.createandshow(mcontext);             //infomodels = new arraylist<>();              // initiate progress             dialog = new progressdialog(mcontext);             this.dialog.setmessage("شکیبا باشید...");             this.dialog.show();              infomodels.clear();         }          @override         protected string doinbackground(string... params) {             okhttpclient client = new okhttpclient();              //string url = (string) params[0];             request request = new request.builder()                     .url(serveraddress + "limit=10")                     .cachecontrol(cachecontrol.force_network)                     .build();              response response;             try {                 response = client.newcall(request).execute();                 ou_response = response.body().string();                 response.body().close();                 if (ou_response != null) {                     try {                         jsonobject postobj = new jsonobject(ou_response);                         jsonarray postsarray = postobj.optjsonarray("result");                         infomodels = new arraylist<>();                          (int = 0; <= postsarray.length(); i++) {                             jsonobject postobject = (jsonobject) postsarray.get(i);                              int id = postobject.getint("id");                             log.d("id", string.valueof(id));                             string title = postobject.getstring("title");                             string description = postobject.getstring("full_description");                             string image = postobject.getstring("image");                             string category = postobject.getstring("categoryname");                             string date = postobject.getstring("publishdate");                              log.d("data", "post id: " + id);                             log.d("data", "post title: " + title);                             log.d("data", "post desc: " + description);                             log.d("data", "post image: " + image);                             log.d("data", "---------------------------------");                              //use title , id per requirement                             infomodels.add(new datamodel(id, title, description, category, date, image));                         }                     } catch (jsonexception e) {                         e.printstacktrace();                         log.e("error", string.valueof(e));                     }                 }             } catch (ioexception e) {                 e.printstacktrace();                 log.e("error2", string.valueof(e));             }             return ou_response;         }          @override         protected void onpostexecute(string result) {             //stop progress             if (dialog.isshowing()) {                 dialog.dismiss();             }             //customprocessdialog.dissmis();             if (result != null) {                 bus.post(new myevent("forfragment2", infomodels));             } else {                 toast.maketext(mcontext, "empty", toast.length_short).show();             }         }     } } 

mainactivity codes :

public class main_page extends appcompatactivity {      private collapsingtoolbarlayout mcollapsingtoolbarlayout;     private toolbar toolbar;     private tablayout tablayout;     private viewpager viewpager;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.main__page);          mcollapsingtoolbarlayout = (collapsingtoolbarlayout) findviewbyid(r.id.collapsing_toolbar_layout);         //mcollapsingtoolbarlayout.settitle(getresources().getstring(r.string.app_name));          toolbar = (toolbar) findviewbyid(r.id.toolbar);         setsupportactionbar(toolbar);         //getsupportactionbar().setdisplayhomeasupenabled(true);          viewpager = (viewpager) findviewbyid(r.id.viewpager);         setupviewpager(viewpager);          tablayout = (tablayout) findviewbyid(r.id.tabs);         tablayout.setupwithviewpager(viewpager);         setuptabicons();     }      /**      * adding custom view tab      */     private void setuptabicons() {          textview tabone = (textview) layoutinflater.from(this).inflate(r.layout.custom_tab, null);         tabone.settext(r.string.free_fragment_title);         tabone.setcompounddrawableswithintrinsicbounds(0, r.drawable.ic_download_image, 0, 0);         tablayout.gettabat(0).setcustomview(tabone);          textview tabtwo = (textview) layoutinflater.from(this).inflate(r.layout.custom_tab, null);         tabtwo.settext(r.string.paid_fragment_title);         tabtwo.setcompounddrawableswithintrinsicbounds(0, r.drawable.ic_paid_download_image, 0, 0);         tablayout.gettabat(1).setcustomview(tabtwo);          textview tabthree = (textview) layoutinflater.from(this).inflate(r.layout.custom_tab, null);         tabthree.settext(r.string.pdf_fragment_title);         tabthree.setcompounddrawableswithintrinsicbounds(0, r.drawable.ic_pdf_icon, 0, 0);         tablayout.gettabat(2).setcustomview(tabthree);     }      /**      * adding fragments viewpager      * @param viewpager      */     private void setupviewpager(viewpager viewpager) {         viewpageradapter adapter = new viewpageradapter(getsupportfragmentmanager());         adapter.addfrag(new free_fragment(), "رایگان ها");         adapter.addfrag(new paid_fragment(), "پرداختی ها");         adapter.addfrag(new pdf_fragment(), "مقالات");         viewpager.setadapter(adapter);     }      class viewpageradapter extends fragmentpageradapter {         private final list<fragment> mfragmentlist = new arraylist<>();         private final list<string> mfragmenttitlelist = new arraylist<>();          public viewpageradapter(fragmentmanager manager) {             super(manager);         }          @override         public fragment getitem(int position) {             return mfragmentlist.get(position);         }          @override         public int getcount() {             return mfragmentlist.size();         }          public void addfrag(fragment fragment, string title) {             mfragmentlist.add(fragment);             mfragmenttitlelist.add(title);         }          @override         public charsequence getpagetitle(int position) {             return mfragmenttitlelist.get(position);         }     } 

how can fix , load fragment data show fragment ? <3

there callback method gets invoked when fragment visible user. can trigger loaddata() in method. have boolean tells if data fetched. refer below lines of code :

in fragment code add following method.

@override   public void setuservisiblehint(boolean isvisibletouser) {      misvisibletouser = isvisibletouser;      if (isvisibletouser && !isdatafetched && getcontext() != null) {      context = getcontext();      loaddata(); //remove call oncreateview      }   } 

in onevent method make following change.

@subscribe public void onevent(myevent event) {     list<datamodel> datamodels = event.getinfomodels();      if (event.fragmenttag.equals("forfragment1")) {         madapter.add(datamodels);         isdatafetched = true;         madapter.notifydatasetchanged();     } } 

add instance variable in fragment code.

private boolean isdatafetched; private boolean misvisibletouser; 

finally modify oncreateview()

   if(misvisibletouser)        loaddata(); 

make sure these changes both fragments.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -