im wondering how androids garbage collector works with data that is kept by the fragment (retain instance).
If I have a Class hirarchy like this:
class MyFragment extends Fragment {
private DataManager dataManager;
public MyFragment(){
setRetainInstance(true);
}
public void onCreate(){
if (dataManager == null)
dataManager = new DataManager();
dataManager.setView(this);
}
public void onCreateView(){
// display the data of the dataManager
}
public void onStop(){
dataManager.setView(null);
}
}
class DataManager implements DataChangedListener {
private MyFragment view;
private Data data;
public DataManager(){
data.setDataChangedListener(this);
}
public void setView(MyFragment v){
this.view = v;
}
}
class Data {
public void setDataChangedListener(DataChangedListener l){
this.listener = l;
}
}
So what i want to do is, that on orientation
change the fragments view content will be recreatd. But the underlying data (DataManager
and Data) must not reload.
The DataManager
listen to the Data Object for changes, an will forward this changes to the UI, the Fragment
. Fragment
is "attached" to the DataManager
when its (re)created.
So far so good. It seems to me a good Solution and well structured. Basically its some kind of Model-View-Presenter pattern.
But now im wondering, when Android will run the garbage collector to collect the DataManager
and Data Objects.
Assume I have an Activity that displays MyFragment
.
But what happens to the memory, when the user of the App navigates to another Activity, that displays something completely different.
Since there is a reference from DataManager
to Data and vice versa, I guess that the data will be kept "forever" in memory, right?
So I guess the garbage collector will only remove this both when the device is going on low memory. But I guess, that these two objects would not be automatically the first two data objects that were garbage collected. I guess there is some kind of "memory deadlock".
What do you think? Any suggestions?