DesperateTears
DesperateTears

Reputation: 23

How to clear memory from pictures of previous layouts? How to clean memory when go to different layout/activity?

My app consists from 4 layout files, each layout uses a different image as background. I manage to load layout 1 and 2, but after I go to layout 3 I get error "Caused by: java.lang.OutOfMemoryError"

I suspect it's because the layout 1 and layout 2 is still in the memory. Any way is there a way to clean memory everytime I go to a new layout so I don't run out of memory? Thanks.

P.S I use Android Studio.

P.S 2 I'm not sure if this changes anything but just in case this is how I go to different activities/layouts:

previouspage.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(), secondPage.class);
                        startActivity(intent);
                    }
                }
        );

        nextpage.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(), FourthPage.class);
                        startActivity(intent);
                    }
                }
        );

Upvotes: 1

Views: 2767

Answers (1)

David
David

Reputation: 16277

new Button.OnClickListener() {
      public void onClick(View v) {
         Intent intent = new Intent(v.getContext(), secondPage.class);
         startActivity(intent);

         yourExistingActivity.finish();  // This will free the memory

}

Note that the activity you're calling the finish() method from is destroyed and ALL its resources are queued for garbage collection, and all memory that was used by this activity will be freed during next GC cycle.

If you really want to revoke the memory as soon as possible, override your activities' onDestroy method:

@Override
public void onDestroy() {
    super.onDestroy();
    Runtime.getRuntime().gc();      
}

Upvotes: 3

Related Questions