5

I create a android application.Select image from gallery using a button and retrieve in the ImageView. The image fetching is successful. Now I want to saved the state of the selected Image.I try to fix.It makes crash application.When I change the Horizontal orientation the app is crashed.Please help me to solve the issue.

My Code :

public class MainActivity extends ActionBarActivity {

ImageView imgBackground;
Button loadImgBtn;

String imgDecodableString;
Drawable drawable;

private static int RESULT_LOAD_IMG = 1;
private static final String IMAGE_DATA = "image_resource";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    loadImgBtn = (Button)findViewById(R.id.btnSelectImage);
    imgBackground = (ImageView)findViewById(R.id.myImg);


    loadImgBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /* Create intent to open Image Application like Gallery */
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            /* start the Intent */
            startActivityForResult(galleryIntent,RESULT_LOAD_IMG);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
            /* Get the Image from Data */
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            /* Get the Cursor */
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn,null,null,null);

            /* Move the first row */
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

            /* Rendering the Image */
            drawable =  new BitmapDrawable(imgDecodableString);
            imgBackground.setBackgroundDrawable(drawable);
        }
    } catch (Exception e) {
        message(getBaseContext()," Error : " + e.getMessage(),Toast.LENGTH_SHORT);
    }
}

public void message(Context ctx,String msg,int duration) {
    Toast.makeText(ctx,msg,duration).show();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
     super.onSaveInstanceState(outState);
     outState.putParcelable(IMAGE_DATA, (android.os.Parcelable) drawable);
}

@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    drawable = (Drawable) savedInstanceState.getParcelable(IMAGE_DATA);
}
}
4

2 回答 2

1

我没有测试过这个,所以我不知道它是否有效。希望是。

但是你应该意识到这一点

...您可能无法使用系统通过 onSaveInstanceState() 回调为您保存的 Bundle 完全恢复您的活动状态 - 它并非旨在承载大型对象(例如位图)和其中的数据必须先序列化然后反序列化,这会消耗大量内存并使配置更改变慢。在这种情况下,您可以通过在您的活动因配置更改而重新启动时保留一个有状态的对象来减轻重新初始化活动的负担。

public class MainActivity extends ActionBarActivity {

        ImageView imgBackground;
        Button loadImgBtn;

        String imgDecodableString;
        BitmapDrawable drawable;

        private static int RESULT_LOAD_IMG = 1;
        private static final String IMAGE_DATA = "image_resource";


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            loadImgBtn = (Button)findViewById(R.id.btnSelectImage);
            imgBackground = (ImageView)findViewById(R.id.myImg);


            loadImgBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
            /* Create intent to open Image Application like Gallery */
                    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            /* start the Intent */
                    startActivityForResult(galleryIntent,RESULT_LOAD_IMG);
                }
            });

            if(savedInstanceState != null) {
                Bitmap tmp = savedInstanceState.getParcelable(IMAGE_DATA);
                if(tmp != null) {
                    drawable = new BitmapDrawable(getResources(), tmp);
                    imgBackground.setImageDrawable(drawable);
                }
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            try {
                if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
            /* Get the Image from Data */
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };

            /* Get the Cursor */
                    Cursor cursor = getContentResolver().query(selectedImage,filePathColumn,null,null,null);

            /* Move the first row */
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    imgDecodableString = cursor.getString(columnIndex);
                    cursor.close();

            /* Rendering the Image */
                    drawable =  new BitmapDrawable(imgDecodableString);
                    imgBackground.setBackgroundDrawable(drawable);
                }
            } catch (Exception e) {
                message(getBaseContext()," Error : " + e.getMessage(), Toast.LENGTH_SHORT);
            }
        }

        public void message(Context ctx,String msg,int duration) {
            Toast.makeText(ctx,msg,duration).show();
        }

        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            if(drawable != null && drawable.getBitmap() != null) {
                outState.putParcelable(IMAGE_DATA, drawable.getBitmap());
            }
        }

        @Override
        protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
        }
    }

}
于 2015-04-23T15:16:01.470 回答
1

将实例状态与位图一起使用时要小心。正如 Bojan 所引用的,您不应将通过“onSaveInstanceState”管理的 Bundle 用于图像。

这是更新的报价:

您可能无法使用系统通过 onSaveInstanceState() 回调为您保存的 Bundle 完全恢复您的活动状态 - 它并非设计用于携带大型对象(例如位图),并且其中的数据必须被序列化然后反序列化,这会消耗大量内存并使配置更改变慢。在这种情况下,您可以通过在您的活动因配置更改而重新启动时保留一个片段来减轻重新初始化活动的负担。此片段可以包含对您要保留的有状态对象的引用。

来自官方文档

你可以找到我按照这个提示实现的代码,看看我对这个其他问题的回答

于 2016-04-02T13:08:26.657 回答