I am using LeakCanary to monitor memory leaks in my mobile app in Android Studio. They were found in an activity that makes a FragmentTransaction operation with two Fragments. They are both instantiated with "new" keyword and in onCreate method another method is used "setFragment(fragment)" passing each Fragment as an argument depending on a bottomNavigationMenu selection. And finally inside the setFragment(fragment) method is being used the "getSupportFragmentManager().beginTransaction().replace(R.id.main_frame, fragment).commit();" function.
This is the code:
public class YouTubeActivity extends AppCompatActivity {
private final NetworkFragment networkFragment = new NetworkFragment();
private final MyListFragment myListFragment = new MyListFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_you_tube);
BottomNavigationView bottomNavigationMenu = findViewById(R.id.bottomNavigationMenu);
setFragment(networkFragment);
bottomNavigationMenu.setSelectedItemId(R.id.search_YouTube);
bottomNavigationMenu.setOnNavigationItemSelectedListener(item -> {
if(item.isChecked())
return true;
else{
if(item.getItemId() == R.id.search_YouTube){
setFragment(networkFragment);
return true;
}else if(item.getItemId() == R.id.search_my_list){
setFragment(myListFragment);
return true;
}else{
setFragment(networkFragment);
return true;
}
}
});
Objects.requireNonNull(getSupportActionBar()).setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_action_bar_3);
}
private void setFragment(Fragment fragment){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_frame, fragment)
.commit();
}
}
How can I make this FragmentTransaction without leaking memory? I read about Weak Reference, is it an option?
Many thanks in advance!
I managed to get rid of those awful memory leaks just by moving the instantiation of the two Fragments inside the NavigationItemSelectedListener and dropping the setFragment(fragment) method!
This tutorial helped me a lot: https://www.youtube.com/watch?v=tPV8xA7m-iw&ab_channel=CodinginFlow (this guy is really talented!)