I'm very new to android and I need your help.
I'm curious if what I do is the right thing or not.
My application has just only one Activity(MainActivity It's AppCompatActivity btw).
But I use several Fragment instead.
Some of Fragments contain an Object(I call it ProblemClass) that must have Activity(not Context though).
Such as ListView's Adapter(or something like that) to inflate Layout
or Dialog that have to inflate Layout and need Context to create AlertDialog.Builder .
And it(ProblemClass) can't call getActivity().
In my mind I have two solution.
1.Pass Activity to ProblemClass.
2.Holding Activity in Singleton for use across whatever Class entire application.
I chose the latter. But...
I have read somewhere that it may cause memory leaked, right?
Since Singleton-Object exist entire application lifetime.
.
.
This is my Singleton that hold Activity.
I call setMyActivity(MainActivity.this) in onCreate() in MainActivity to pass it to Singleton.
public class MyActivitySingleton
{
private AppCompatActivity mAppCompatActivity;
private MyActivitySingleton()
{
}
private static class MyActivitySingletonHolder
{
private static final MyActivitySingleton INSTANCE = new MyActivitySingleton();
}
public static MyActivitySingleton getInstance()
{
return MyActivitySingletonHolder.INSTANCE;
}
public AppCompatActivity getMyActivity()
{
return this.mAppCompatActivity;
}
public void setMyActivity(AppCompatActivity appCompatActivity)
{
this.mAppCompatActivity = appCompatActivity;
}
}
Any suggestion? What do I have to do?
Pass an Activity to ProblemClass and if it need Context. It can use Activity as a Context too?
Thanks.