• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Fragments and memory

Fl_Op

Lurker
Hy,

I am developing an application with Fragments. Here is my (simplified) code.

Java:
public class MainActivity extends AppCompatActivity{
    private FragmentManager fm = null;
    private Fragment fragment = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // ...

        FragmentManager fm = getSupportFragmentManager();
        fragment = Fragment1.newInstance();
        fm.beginTransaction().replace(R.id.content_to_replace,fragment).commit();
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.fragment_1) {
            fragment = Fragment1.newInstance();
            idFragment = 0;
        } else if (id == R.id.fragment_2) {
            fragment = Fragment2.newInstance();
            idFragment = 1;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        fm.beginTransaction().replace(R.id.content_to_replace,fragment).commit();
        return true;
    }
}

I thought that in "onNavigationItemSelected", the replaced fragment will free the memory that it took. But I see that if I switch fragments many times, the free memory will always decrease.

RAM_android.png



So, I would like to know why, and if I can prevent this from happening

Thanks in advance for your answers.
 
Are you asking why the consumed memory doesn't decrease?
The garbage collector makes its own decisions on when to free up memory. It may not behave as you expect. Each time you call Fragment.newInstance() an object is created on the heap. Periodically the GC decides which objects are unreferenced and cleans them up. Or it may decide to defer this action. With GC, you cannot rely on predictable behaviour. As the memory consumed by your program increases, the GC may decide to do more rigorous cleaning up.
 
Are you asking why the consumed memory doesn't decrease?
The garbage collector makes its own decisions on when to free up memory. It may not behave as you expect. Each time you call Fragment.newInstance() an object is created on the heap. Periodically the GC decides which objects are unreferenced and cleans them up. Or it may decide to defer this action. With GC, you cannot rely on predictable behaviour. As the memory consumed by your program increases, the GC may decide to do more rigorous cleaning up.
Thanks, I made the test with a loop which create many Fragments, and you're right.
 
Back
Top Bottom