Mohammad Mohammad - 6 months ago 112
Android Question

Android: setImageBitmap from sdCard not work

I want select photo by user from sd card and show in ImageView

My code :

try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
}
catch (IOException e) {
e.printStackTrace();
}
imgOne.setImageBitmap(bm);


But this code not work

This code for onActivityResult after select photo by user


My class :


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Log.i("error", "" + requestCode);
final ImageView imgOne = (ImageView) G.currentActivity.findViewById(R.id.imgOne);
if (requestCode == 1) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
//ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//bm.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

//bm = Bitmap.createScaledBitmap(bm, 600, 600, true);
}
catch (IOException e) {
e.printStackTrace();
}

imgOne.setImageBitmap(bm);
Log.i("error", "" + bm);
}
}
}
}

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

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

      final Uri imageUri = data.getData();
                final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

                imageView.setImageBitmap(selectedImage);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
Comments