2

My app is supposed to first displays an image, when a button is pressed, another image is displayed in the image view. However, when the screen is rotated, the imageView displays the old image. How should I go about fixing this? (bits is the Bitmap loaded into imageView on create)

My code is below:

    RGBToBitmap(rgb.getWindow(), bits); //this loads a new image into bits

    imageView.setImageBitmap(bits);
jop
  • 121
  • 1
  • 2
  • 9

1 Answers1

7

I suppose you are setting the first image of your ImageView in the onCreate or onStart method of your Activity.

Upon rotating the screen, the onCreate and onStart methods get called again, and therefore your ImageView displays the first image again.

In order to save your Activity state, have a look at this: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState

This could be a possible solution:

Bitmap image = null;

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

 image = (Bitmap) getLastNonConfigurationInstance();

     if(bitmap == null){
         image = downloadImage();
      }
     setImage(bitmap);
}


@Override
public Object onRetainNonConfigurationInstance() {
    return bitmap;
}

You can also read into this method when ur using fragments:

Fragment.setRetainInstance

Or the Bundle: (onSaveInstanceState(Bundle) is also available in your Activity)

//Save it onSaveInstanceState:

  @Override
  public void onSaveInstanceState(Bundle toSave) {
    super.onSaveInstanceState(toSave);
    toSave.putParcelable("bitmap", bitmap);
  }
//nd get it back onCreate:

 @Override
  public void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    if (savedState != null) bitmap = savedState.getParcelable("bitmap");
  }
Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187