java - What is going on with my Android Navigation drawer activity? -


i building opengl live wallpaper. decided have navigation drawer in main activity since there lot of features user have access to.

the problem/issue if press "hardware" button close app initial fragment shown refreshes , app never closes. if hit home button , go app black screen. i've searched throughout google thinking maybe wasn't destroying mainactivity or way terminate fragment. i've tried calling finish() in main activity's ondestroy method. i've tried utilizing remove method fragment manager in each fragments ondetach method per posts i've found online. nothing has worked. i'm stumped. i've set debug points in main activity on ondestroy method , on fragments ondetach method no error being produced or information being given. @ point clueless. here's mainactivity class.

    public class mainactivity extends appcompatactivity implements onnavigationitemselectedlistener, onpostselectedlistener{      fragmentmanager mfragmentmanager;     fragmenttransaction mfragmenttransaction;     textview usrtag, tagremail;     circleimageview tagrpic;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);          setcontentview(r.layout.activity_main);         toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar);         setsupportactionbar(toolbar);          drawerlayout drawer = (drawerlayout) findviewbyid(r.id.drawer_layout);          actionbardrawertoggle toggle = new actionbardrawertoggle(                 this, drawer, toolbar, r.string.navigation_drawer_open, r.string.navigation_drawer_close);         drawer.setdrawerlistener(toggle);         toggle.syncstate();          mfragmentmanager = getsupportfragmentmanager();         mfragmenttransaction = mfragmentmanager.begintransaction();         mfragmenttransaction.add(r.id.clmain, new previewfragment()).addtobackstack("previewfragment").commit();          navigationview navigationview = (navigationview) findviewbyid(r.id.nav_view);         navigationview.setnavigationitemselectedlistener(this);         view header = navigationview.getheaderview(0);         usrtag = (textview)header.findviewbyid(r.id.usrname);         tagremail = (textview)header.findviewbyid(r.id.usremail);         tagrpic = (circleimageview)header.findviewbyid(r.id.usrimg);          log.i("mainactivity: ", "user photo: " + getprofilepic(this));          usrtag.settext(getusername(getbasecontext()));         tagremail.settext(getuseremail(getbasecontext()));         glideutils.loadprofileicon(getprofilepic(getbasecontext()), tagrpic);      }      @override     public void onbackpressed() {         drawerlayout drawer = (drawerlayout) findviewbyid(r.id.drawer_layout);         if (drawer.isdraweropen(gravitycompat.start)) {             drawer.closedrawer(gravitycompat.start);         } else {             super.onbackpressed();           }     }      @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.main, menu);         return true;     }      @override     public boolean onoptionsitemselected(menuitem item) {          int id = item.getitemid();          //noinspection simplifiableifstatement         if (id == r.id.action_settings) {             return true;         }          return super.onoptionsitemselected(item);     }      @suppresswarnings("statementwithemptybody")     @override     public boolean onnavigationitemselected(menuitem item) {         // handle navigation view item clicks here.         fragment fragment = null;         class fragmentclass = null;         int id = item.getitemid();          if (id == r.id.nav_home) {             fragmentclass = previewfragment.class;         } else if (id == r.id.nav_custom) {             startcustomlabelcreator();         } else if (id == r.id.nav_mylabels) {          } else if (id == r.id.nav_commlabels) {             fragmentclass = postsfragment.class;         } else if (id == r.id.nav_share) {          } else if (id == r.id.nav_send) {          }          try {             fragment = (fragment) fragmentclass.newinstance();         } catch (exception e) {             e.printstacktrace();         }          // insert fragment replacing existing fragment         fragmentmanager fragmentmanager = getsupportfragmentmanager();         fragmentmanager.begintransaction().replace(r.id.clmain, fragment).commit();          drawerlayout drawer = (drawerlayout) findviewbyid(r.id.drawer_layout);         drawer.closedrawer(gravitycompat.start);         return true;     }      public void startcustomlabelcreator(){         intent clc = new intent(getbasecontext(), createlabel.class);         startactivity(clc);     }      @override     public void onpostcomment(string postkey) {      }      @override     public void onpostlike(string postkey) {      }      @override     public void onphotoselected(string photourl) {      }      @override     protected void ondestroy() {         super.ondestroy();         finish();     } } 

my fragments

    public class postsfragment extends fragment implements confirmselectedphotolistener{      public static final string tag = "postsfragment";     private static final string key_layout_position = "layoutposition";     private int mrecyclerviewposition = 0;     private onpostselectedlistener mlistener;       private recyclerview mrecyclerview;     private recyclerview.adapter<postviewholder> madapter;      public postsfragment() {         // required empty public constructor     }      public static postsfragment newinstance() {         postsfragment fragment = new postsfragment();         return fragment;     }      @override     public void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);     }      @override     public view oncreateview(layoutinflater inflater, viewgroup container,                              bundle savedinstancestate) {         view rootview = inflater.inflate(r.layout.fragment_posts, container, false);         rootview.settag(tag);          mrecyclerview = (recyclerview) rootview.findviewbyid(r.id.my_recycler_view);         return rootview;     }      @override     public void onactivitycreated(bundle savedinstancestate) {         super.onactivitycreated(savedinstancestate);         linearlayoutmanager linearlayoutmanager = new linearlayoutmanager(getactivity());         linearlayoutmanager.setreverselayout(true);         linearlayoutmanager.setstackfromend(true);         mrecyclerview.setlayoutmanager(linearlayoutmanager);          log.d(tag, "restoring recycler view position (all): " + mrecyclerviewposition);         query allpostsquery = firebaseutil.getpostsref();         madapter = getfirebaserecycleradapter(allpostsquery);         madapter.registeradapterdataobserver(new recyclerview.adapterdataobserver() {             @override             public void onitemrangeinserted(int positionstart, int itemcount) {                 super.onitemrangeinserted(positionstart, itemcount);                 // todo: refresh feed view.             }         });           mrecyclerview.setadapter(madapter);     }      private firebaserecycleradapter<post, postviewholder> getfirebaserecycleradapter(query query) {         return new firebaserecycleradapter<post, postviewholder>(                 post.class, r.layout.post_item, postviewholder.class, query) {             @override             public void populateviewholder(final postviewholder postviewholder,                                            final post post, final int position) {                 setuppost(postviewholder, post, position, null);             }              @override             public void onviewrecycled(postviewholder holder) {                 super.onviewrecycled(holder); //                firebaseutil.getlikesref().child(holder.mpostkey).removeeventlistener(holder.mlikelistener);             }         };     }      private void setuppost(final postviewholder postviewholder, final post post, final int position, final string inpostkey) {         postviewholder.setphoto(post.getthumb_url());         log.d(tag, post.getthumb_url());         postviewholder.settext(post.gettext());         postviewholder.settimestamp(dateutils.getrelativetimespanstring(                 (long) post.gettimestamp()).tostring());         final string postkey;         if (madapter instanceof firebaserecycleradapter) {             postkey = ((firebaserecycleradapter) madapter).getref(position).getkey();         } else {             postkey = inpostkey;         }          author author = post.getauthor();         postviewholder.setauthor(author.getfull_name(), author.getuid());         postviewholder.seticon(author.getprofile_picture(), author.getuid());          valueeventlistener likelistener = new valueeventlistener() {             @override             public void ondatachange(datasnapshot datasnapshot) {                 postviewholder.setnumlikes(datasnapshot.getchildrencount());                 if (datasnapshot.haschild(firebaseutil.getcurrentuserid())) {                     postviewholder.setlikestatus(postviewholder.likestatus.liked, getactivity());                 } else {                     postviewholder.setlikestatus(postviewholder.likestatus.not_liked, getactivity());                 }             }              @override             public void oncancelled(databaseerror databaseerror) {              }         };         firebaseutil.getlikesref().child(postkey).addvalueeventlistener(likelistener);         postviewholder.mlikelistener = likelistener;          postviewholder.setpostclicklistener(new postviewholder.postclicklistener() {             @override             public void showcomments() {                 log.d(tag, "comment position: " + position);                 mlistener.onpostcomment(postkey);             }              @override             public void togglelike() {                 log.d(tag, "like position: " + position);                 mlistener.onpostlike(postkey);             }              @override             public void savephotourl() {                 //mlistener.onphotoselected(post.getfull_url());                 showlabelconfirm(post.getfull_url());             }         });     }      @override     public void ondestroy() {         super.ondestroy();         if (madapter != null && madapter instanceof firebaserecycleradapter) {             ((firebaserecycleradapter) madapter).cleanup();         }     }       @override     public void onsaveinstancestate(bundle savedinstancestate) {         // save selected layout manager.         int recyclerviewscrollposition = getrecyclerviewscrollposition();         log.d(tag, "recycler view scroll position: " + recyclerviewscrollposition);         savedinstancestate.putserializable(key_layout_position, recyclerviewscrollposition);         super.onsaveinstancestate(savedinstancestate);     }      private int getrecyclerviewscrollposition() {         int scrollposition = 0;         // todo: null check necessary?         if (mrecyclerview != null && mrecyclerview.getlayoutmanager() != null) {             scrollposition = ((linearlayoutmanager) mrecyclerview.getlayoutmanager())                     .findfirstcompletelyvisibleitemposition();         }         return scrollposition;     }      @override     public void onselectedphoto(string selectphoto) {         mlistener.onphotoselected(selectphoto);     }      public interface onpostselectedlistener {         void onpostcomment(string postkey);         void onpostlike(string postkey);         void onphotoselected(string photourl);     }      private void showlabelconfirm(string uribmp) {         fragmentmanager fm = getfragmentmanager();         photodialogfragment editnamedialogfragment = photodialogfragment.newinstance(uribmp);         // sets target fragment use later when sending results         editnamedialogfragment.settargetfragment(postsfragment.this, 300);         editnamedialogfragment.show(fm, "fragment_edit_name");     }      @override     public void onattach(context context) {         super.onattach(context);         if (context instanceof onpostselectedlistener) {             mlistener = (onpostselectedlistener) context;         } else {             throw new runtimeexception(context.tostring()                     + " must implement onpostselectedlistener");         }     }      @override     public void ondetach() {         super.ondetach();         mlistener = null;     } } 

second fragment:

    public class previewfragment extends rajbasefragment {       @override     public isurfacerenderer createrenderer() {         return new previewrenderer(getcontext());     }   } 

which extends:

    public abstract class rajbasefragment extends fragment implements idisplay, view.onclicklistener {       protected framelayout mlayout;     protected isurface mrajawalisurface;     protected isurfacerenderer mrenderer;      public rajbasefragment(){      }      @override     public void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);       }      @override     public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) {         super.oncreateview(inflater, container, savedinstancestate);          // inflate view         mlayout = (framelayout) inflater.inflate(getlayoutid(), container, false);          mlayout.findviewbyid(r.id.relative_layout_loader_container).bringtofront();          // find textureview         mrajawalisurface = (isurface) mlayout.findviewbyid(r.id.rajwali_surface);          // create loader           mrenderer = createrenderer();         onbeforeapplyrenderer();         applyrenderer();         return mlayout;     }      protected void onbeforeapplyrenderer() {      }      protected void applyrenderer() {         mrajawalisurface.setsurfacerenderer(mrenderer);     }      @override     public void onclick(view v) {      }      @override     public void ondestroyview() {         super.ondestroyview();          if (mlayout != null)             mlayout.removeview((view) mrajawalisurface);     }      @override     public int getlayoutid() {         return r.layout.rajawali_textureview_fragment;     }     } 

i've tried recommendations below far , primary fragment set in mainactivity's oncreate method still gets refreshed/reloaded when button pressed rather app exiting/closing.

in onnavigationitemselected method, replacing current fragment fragment in cases fragment null, has undefined effects. should not that.

one fix replace code block:

try {   fragment = (fragment) fragmentclass.newinstance(); } catch (exception e) {   e.printstacktrace(); } 

with one:

if (fragmentclass != null) {   fragment = fragmentclass.newinstance();   fragmentmanager fragmentmanager = getsupportfragmentmanager();   fragmentmanager.begintransaction().replace(r.id.clmain, fragment).addtobackstack().commit(); } 

(and leave out fragment transaction below point).

also, there call finish in ondestroy method, not causing problem should taken out because not make sense there.


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) -