Niral Bhavsar Niral Bhavsar -4 years ago 138
Android Question

Get image from gallery to set in imageview in fragment?

How to get image from gallary to set in Imageview in fragment ? onActivityResult not called in fragment..this the code i wrote in fragment

img_user.setOnClickListener(new View.OnClickListener() {
@Override
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);


}
});


public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);


if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);

cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
img_user.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close`enter code here`();
} else {
Toast.makeText(getActivity(), "Try Again!!", Toast.LENGTH_SHORT)
.show();
}

}

Answer Source

You can do this in this way....in your main activity

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

and inside your fragment

 Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // ******** code for crop image
                i.putExtra("crop", "true");
                i.putExtra("aspectX", 100);
                i.putExtra("aspectY", 100);
                i.putExtra("outputX", 256);
                i.putExtra("outputY", 356);

                try {

                    i.putExtra("return-data", true);
                    startActivityForResult(
                            Intent.createChooser(i, "Select Picture"), 0);
                }catch (ActivityNotFoundException ex){
                    ex.printStackTrace();
                }

and

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0 && resultCode == Activity.RESULT_OK){
            try {
                Bundle bundle = data.getExtras();
                Bitmap bitmap = bundle.getParcelable("data");
                img_user.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

Works perfect for me

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download