How to fix duplicate data when use Fragment and TabLayout in Android -


i want show website datas in 3 fragments json! when swipe between tabs not duplicate datas. when click on tabs, duplicate previous data again!
send data from asynctask fragments use eventbus component.
fragment 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;     private boolean isdatafetched;     private boolean misvisibletouser;     private view view;      @override     public view oncreateview(layoutinflater inflater,                              viewgroup container, bundle savedinstancestate) {          view = inflater.inflate(r.layout.fragment_free_layout, container, false);          context = getcontext();          if (misvisibletouser) {             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 (datamodels.size() > 0) {             datamodels.remove(datamodels.size() - 1);             madapter.notifyitemremoved(datamodels.size());             //madapter.setloaded();         }*/         if (event.fragmenttag.equals("forfragment1")) {             madapter.add(datamodels);             isdatafetched = true;             madapter.notifydatasetchanged();         }     }      @override     public void setuservisiblehint(boolean isvisibletouser) {         misvisibletouser = isvisibletouser;         if (isvisibletouser && !isdatafetched && getcontext() != null) {             context = getcontext();             loaddata(); //remove call oncreateview         }     }      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();     } } 

asynctask codes:

public class freedatainfo {     private context mcontext;     private string serveraddress = freeserver_ip.getfreeip();     private disklrudatacache mdisklrucache;      public void getfreedatainfo(context context) {         mcontext = context;         this.mdisklrucache=new disklrudatacache(context);         //new getinfo().execute(serveraddress + "limit=10");         new getinfo().execute(serveraddress);     }      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")                     .url(serveraddress)                     .cachecontrol(cachecontrol.force_network)                     .build();              response response;             try {                 if(checkinternet.isconnected(mcontext)) {                     response = client.newcall(request).execute();                     ou_response = response.body().string();                     if (ou_response != null) {                         mdisklrucache.cachetodisk(serveraddress, ou_response);                     }                     response.body().close();                 }                 else{                     ou_response=mdisklrucache.fetchfromdiskcache(serveraddress);                 }                 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("full_description");                             string image = postobject.getstring("image");                             string category = postobject.getstring("categoryname");                             string date = postobject.getstring("date");                             string url = postobject.getstring("url");                              log.d("data", "post id: " + id);                             log.d("data", "post title: " + title);                             log.d("data", "post image: " + image);                             log.d("data", "post url: " + url);                             log.d("data", "---------------------------------");                              //use title , id per requirement                             infomodels.add(new datamodel(id, title, description, category, date, url, 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, "check internet", toast.length_long).show();              }         }     } } 

adapter codes:

public class free_recycler_adapter extends recyclerview.adapter<free_recycler_adapter.viewholder> {     private list<datamodel> mdateset;     private context context;      // provide suitable constructor (depends on kind of dataset)     public free_recycler_adapter(context context, list<datamodel> dataset) {         this.context = context;         this.mdateset = dataset;     }      // create new views (invoked layout manager)     @override     public free_recycler_adapter.viewholder oncreateviewholder(viewgroup parent, int viewtype) {         // create new view         view view = layoutinflater.from(parent.getcontext()).inflate(r.layout.free_card_layout, parent, false);          // create viewholder         return new viewholder(view);     }      // replace contents of view (invoked layout manager)     @override     public void onbindviewholder(viewholder viewholder, final int position) {          // - data itemsdata @ position         // - replace contents of view itemsdata          viewholder.free_titletext.settext(html.fromhtml(mdateset.get(position).gettitle()));         viewholder.free_titletext.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                 v.getcontext().startactivity(new intent(v.getcontext(), contentpage.class)                         .putextra("title", mdateset.get(position).gettitle())                         .putextra("desc", mdateset.get(position).getdescription())                         .putextra("image", mdateset.get(position).getimage())                         .putextra("url", mdateset.get(position).geturl())                         .putextra("category", mdateset.get(position).getcategory())                         .putextra("date", mdateset.get(position).getdate()));             }         });          glide.with(context)                 .load(mdateset.get(position).getimage())                 .placeholder(r.drawable.ic_download_image)                 .crossfade()                 .into(viewholder.free_avatarimage);         viewholder.free_avatarimage.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                 v.getcontext().startactivity(new intent(v.getcontext(), contentpage.class)                         .putextra("title", mdateset.get(position).gettitle())                         .putextra("desc", mdateset.get(position).getdescription())                         .putextra("image", mdateset.get(position).getimage())                         .putextra("url", mdateset.get(position).geturl())                         .putextra("category", mdateset.get(position).getcategory())                         .putextra("date", mdateset.get(position).getdate()));             }         });          viewholder.free_desctext.settext(html.fromhtml(mdateset.get(position).getdescription()));         viewholder.free_desctext.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                 v.getcontext().startactivity(new intent(v.getcontext(), contentpage.class)                         .putextra("title", mdateset.get(position).gettitle())                         .putextra("desc", mdateset.get(position).getdescription())                         .putextra("image", mdateset.get(position).getimage())                         .putextra("url", mdateset.get(position).geturl())                         .putextra("category", mdateset.get(position).getcategory())                         .putextra("date", mdateset.get(position).getdate()));             }         });      }      // return size of dataset (invoked layout manager)     @override     public int getitemcount() {         return mdateset.size();     }      public void remove(int position) {         mdateset.remove(position);         notifyitemremoved(position);     }      public void clear() {         mdateset.clear();         notifydatasetchanged();     }      public void add(list<datamodel> models) {         mdateset.addall(models);         notifydatasetchanged();     }      public void update(list<datamodel> models) {         mdateset.clear();         mdateset.addall(models);         notifydatasetchanged();     }      // inner class hold reference each item of recyclerview     public static class viewholder extends recyclerview.viewholder {          public textview free_titletext, free_desctext;         public imageview free_avatarimage;          public viewholder(view itemlayoutview) {             super(itemlayoutview);              free_titletext = (textview) itemlayoutview.findviewbyid(r.id.pdf_card_title);             free_desctext = (textview) itemlayoutview.findviewbyid(r.id.pdf_card_content);             free_avatarimage = (imageview) itemlayoutview.findviewbyid(r.id.pdf_card_image);          }     } } 

mainactivity codes:

public class main_page extends appcompatactivity {      private collapsingtoolbarlayout mcollapsingtoolbarlayout;     private toolbar toolbar;     private tablayout tablayout;     private viewpager viewpager;      private drawerlayout mdrawer;     private navigationview nvdrawer;     private imageview menuimage;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.main__page);          calligraphyconfig.initdefault(new calligraphyconfig.builder()                 .setdefaultfontpath("fonts/iransans.ttf")                 .setfontattrid(r.attr.fontpath)                 .build());          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().settitle("");         //getsupportactionbar().setdisplayhomeasupenabled(true);          viewpager = (viewpager) findviewbyid(r.id.viewpager);         setupviewpager(viewpager);          tablayout = (tablayout) findviewbyid(r.id.tabs);         tablayout.setupwithviewpager(viewpager);         setuptabicons();          mdrawer = (drawerlayout) findviewbyid(r.id.drawer_layout);         nvdrawer = (navigationview) findviewbyid(r.id.navigation_drawer);         menuimage = (imageview) findviewbyid(r.id.drawablemenu_image);         menuimage.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                 mdrawer.opendrawer(gravitycompat.end);             }         });      }      /**      * 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);         }     }      @override     public void onbackpressed() {         if (mdrawer.isdraweropen(gravitycompat.end)) {             mdrawer.closedrawers();         } else             super.onbackpressed();     }      @override     protected void attachbasecontext(context newbase) {         super.attachbasecontext(calligraphycontextwrapper.wrap(newbase));     }  } 

how can fix , not duplicate datas when click on tablayout ?
amateur , need help, please me. all<3

check commented code : it's causing datamodels added every time adapter.

@subscribe public void onevent(myevent event) {        list<datamodel> datamodels = event.getinfomodels();         if (event.fragmenttag.equals("forfragment1")) {                 //madapter.add(datamodels);                 isdatafetched = true;                 madapter.notifydatasetchanged();        } } 
  • in adapter, in add() method, adding data list on again, unnecessary, calling notifydatasetchanged automatically intimates adapter original data has been changed.

  • just call notifydatasetchanged on adapter refresh updated data. hope helps.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -