I would like to know whether it's a bad design choice to use a singleton MainAcitivity as in the following:
public class MainActivity extends AppCompatActivity ... {
public static MainActivity mainActivitySingleton;
....
@Override
protected void onCreate(Bundle savedInstanceState) {
mainActivitySingleton=this;
For instance, in many occasions where I need to access the context I use getContext()
, but sometimes (I don't know why) getContext()
returns null
resulting in a runtime exception. I ended up using the mainActivitySingleton
I created instead of getContext()
.
My little finger tells me this is a bad design choice! if it is the case, can anyone explain why?
Never do that. That is the bad design pattern. You should not save activity instance as static instance, because that potential memory leak. If you call getContext()
method in fragment instance then you should call getContext()
in this lifecircle onActivityCreated()
method.
Like this:
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Context context = getContext();
}