Reputation: 11
This is my first time programming for mobile. My app has been crashing when I switch from one fragment to another. In logcat after one crash it showed me "java.lang.OutOfMemoryError" among a litany of other things. I think it's because my first fragment has a photo and the second does as well. Is there a simple way to make sure that a fragment is out of memory once another is loaded? I've looked around quite a bit but haven't found any straightforward answers.
Here's the code for switching fragments as is...
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
if (id == R.id.nav_home) {
fragment = new LandingPageFragment();
} else if (id == R.id.nav_documents) {
fragment = new DocumentsPageFragment();
}
else if (id == R.id.nav_messages) {
fragment = new MessagesFragment();
}
else if (id == R.id.nav_admin) {
fragment = new AdministrationFragment();
}
else{
fragment = new LandingPageFragment();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit();
this.prevFragment = fragment;
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout_new);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Upvotes: 1
Views: 530
Reputation: 100
I don't think there is a way of knowing when OutOfMemoryError
get's thrown, but the important thing you have to do is making sure you are not loading very big images to your ImageViews
. The best thing you could do is scale the images down before loading them into your ImageView
s. This fixes the OOM issue. You can use the code in this guide to scale down the images: Android developers
Upvotes: 1