android - Fragment getActivity() -- avoiding NPE -


i have single activity application number of fragments (15 or so). of methods in myactivity required fragments, such displaying dialogs. have in sample call fragment (and extend myfragment) like:

getmyactivity().displaydialog(msg);

and getmyactivity defined in myfragment:

myactivity getmyactivity() {   return (myactivity) getactivity(); } 

however, getactivity() null npes in case. i'm doing moving methods myfragment such that:

protected void displaydialog(string msg) {   if (getmyactivity() != null) {      getmyactivity().displaydialog(msg);   } else {      // do here?   } } 

does approach make sense 10 or methods need reference myactivity (and there pitfalls doing so)? also, provide feedback in case getactivity() null?

edit: common example of cause nullpointerexception network call being dispatched fragment , on completion of said network call, trying display dialog when activity destroyed in meantime.

its better use parentfragment example

public abstract class parentfragment extends fragment {  public activity activity;  @override public void onattach(activity activity) {     super.onattach(activity);     this.activity = activity; }  } 

then must owerride yor fragments

public class somefragment extends parentfragment {} 

and use there activity for

activity.displaydialog(msg); 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -