Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get selected image from gallery into imageview

Tags:

android

xml

I am facing a problem in selecting the image from a gallery and setting it into the imageview. Suppose I have two activities; mainActivity containing buttons for gallery and secondactivity containing the imageview in which the image has to be displayed.

 b1.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    Intent i = new Intent(
    Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, RESULT_LOAD_IMAGE);
   }
   });

Please give me the individual code for both....

like image 943
amanjain4all Avatar asked Nov 25 '13 15:11

amanjain4all


1 Answers

here is the code to load an image from gallery:

public class ImageGalleryDemoActivity extends Activity {


    private static int RESULT_LOAD_IMAGE = 1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

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

            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }


    }
}
like image 179
Hamad Avatar answered Oct 17 '22 00:10

Hamad