2012년 3월 14일 수요일

ImageView disapears when changing to portrait/landscape


ImageView disapears when changing to portrait/landscape







Q  :

I have an imageview with a bitmap picture on it. i set this picture in the onActivityResault. the problem is when i change to portrait/landscape the image disapears.
protected void onActivityResult(int requestCode,int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case 1:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            InputStream imageStream;
            try {
                imageStream = getContentResolver().openInputStream(selectedImage);
                Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
                image.setImageBitmap(yourSelectedImage);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
A :
When orientation changes activity is destroyed and created again. If you're creating your layout using xml all widgets having @id set, should be automatically recreated with it's content. Otherwise you have to do that manually - take a look at Activity's methods onRestoreInstanceState() onSaveInstanceState() just override them and write your own save/restore code. Some of untested code, hope, that it will give you an idea:
@Override
onSaveInstanceState(Bundle b){
b.putParcelable("image", image.getBitmap());
}
@Override
onRestoreInstanceState(Bundle b){
//you need to handle NullPionterException here.
image.setBitmap((Bitmap)b.getParcelable("image"));
}
link|improve this answer
Thanks, but can you explain this a bit more? I have a Bitmap object in my activity, how do i set the image view picture to that bitmap again on those methods? – Yuval Jul 16 '11 at 11:17
I've edited my answer. – piotrpo Jul 16 '11 at 18:09