I'm trying to get an image by starting an Intent
to select from the photo gallery using startActivityForResult
and by overriding onActivityResult
. I don't know why, but when I select an image and try to draw it on my screen, nothing happens. I'm able to select the image, and then that's it.
I searched for answers but couldn't find anything that helped. There doesn't seem to be much that I can try to fix this problem. I believe I've implemented everything correctly. This is also my first time trying this though so I could be wrong. I've overrided the onActivityResult
to get a bitmap and set a bitmap variable from another class with it when I call getGalleryImage()
.
Starting the Intent from my GameView class:
MainActivity activity = (MainActivity) context;
public void getGalleryImage() {
Intent gallery = new Intent(Intent.ACTION_PICK);
gallery.setType("image/*");
String[] mimeTypes = { "image/png" };
gallery.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
activity.startActivityForResult(gallery, 1);
}
Override Method in MainActivity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == MainActivity.RESULT_OK) {
final Uri uri = data.getData();
InputStream in;
try {
in = getContentResolver().openInputStream(uri);
final Bitmap selected_img = BitmapFactory.decodeStream(in);
view.setSelectedImage(selected_img);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "An error occured!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "You didn't pick an image!", Toast.LENGTH_LONG).show();
}
}
}
I want to get the image and draw it to my screen. What's happening is I select the image after the intent opens, and then nothing. It goes back to my activity and nothing seems to be drawing at all.
As it seems like your View.setSelectedImage()
comes from a custom class, you might want to try trying to draw the Bitmap
on ImageView
first to see if it works.
Use ImageView
instead and call ImageView.setImageBitmap(bitmap)
from within onActivityResult()
. And make sure decoded bitmap isn't too large as it can cause your app to stutter and you might want to try loading large bitmap efficiently.
Also, update your getGalleryImage()
method to this:
public void getGalleryImage() {
final Intent galleryIntent = Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 1);
}