Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an application where I take a picture and set it as the image on image button. On change in orientation, the image vanishes. Please help.

I click a picture and set it as the image on the ImageItem

public void onImageButtonClicked(View view)
{
    Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(camIntent, TAKE_PHOTO);
}


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == TAKE_PHOTO && resultCode == Activity.RESULT_OK)
        try {
            InputStream stream = getContentResolver().openInputStream(data.getData());
            Bitmap bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            ImageButton imageButton = (ImageButton) findViewById(R.id.itemImage);

            int mDstWidth = getResources().getDimensionPixelSize(R.dimen.destination_width);
            int mDstHeight = getResources().getDimensionPixelSize(R.dimen.destination_height);

            scaledBmp = Bitmap.createScaledBitmap(bitmap, mDstWidth, mDstHeight, true);
            imageButton.setImageBitmap(scaledBmp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    super.onActivityResult(requestCode, resultCode, data);
}

When the orientation is changed, image disappears.

I saved the image in 

@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
    super.onSaveInstanceState(savedInstanceState);
    if (scaledBmp != null) {
        savedInstanceState.putByteArray("image", getBitmapAsByteArray(scaledBmp));
    }
}


and retrieved in 

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    byte[] savedImage;
    savedImage = savedInstanceState.getByteArray("image");
    if (savedImage != null) {
        scaledBmp = BitmapFactory.decodeByteArray(savedImage, 0, savedImage.length -1);
    }
}

Should I set the image on the button manually now? Is there something I am missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

I was missing onResume()

protected void onResume()
{
    super.onResume();
    if (scaledBmp != null)
    {
        ImageButton ib = (ImageButton) findViewById(R.id.itemImage);
        if (ib != null)
            ib.setImageBitmap(scaledBmp);
    }
}

With this change, things started working. I am getting the image in landscape as well as portrait mode.

Asthme's comment helped me, thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...