Question

I'm writing an app that stores a String in an SQLite database, which represents the filepath of an image on the /sdcard/. I have this code in the onCreate() one of my activities:

final Intent receivedIntent = getIntent();

String imageStr = receivedIntent.getExtras().getString("picture");
ImageView imageView = (ImageView) findViewById(R.id.pPicture);
File file = new File (imageStr);
if (file.exists()) {
   Bitmap bitmap = BitmapFactory.decodeFile(imageStr);
   imageView.setImageBitmap(bitmap);
}

The code works when I'm first loading the activity, but when I switch between screen orientations, it crashes my application. Any ideas on what I can do to fix this? I'd like to bee able to continue switching between orientations, but I don't need to refresh each time.

Also, I'm somewhat new, so please try to keep your answers not too complicated if possible.

Note that the file does exist in all cases.

Was it helpful?

Solution

I think your app crashes because of OutOfMemoryException. Try recylcing the bitmap in onDestroy():

@Override
public void onDestroy() {
    super.onDestroy();

    ImageView imageView = (ImageView) findViewById(R.id.pPicture);
    Drawable drawable = imageView.getDrawable();
    imageView.setImageDrawable(null);

    if (drawable instanceof BitmapDrawable) {
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        bitmap.recycle();
        bitmap = null;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top