Android: Gallery intent returning resultCode == RE

2019-03-27 21:05发布

问题:

I'm starting an intent to pick a picture from the gallery but the intent always returns with the resultcode RESULT_CANCELED. I have tried alot of different code but nothing helps wich makes me think maybe I am missing something, like putting something in the activity in the Android manifest?

My Code:

// The Intent
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);

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

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK){
        Uri targetUri = data.getData();
        Bitmap bitmap;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
            profileImage.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Would appreciate some help ;)

回答1:

OK so I solved this. My problem turned out to be that the onActivityResult() method was being called before the Gallery Intent had finished. I found the sollution here: onActivityResult() called prematurely

Basically, I had specified the activity to be "singleTask" in the manifest. Changing it to "singleTop" solved it for me.



回答2:

That saved my life! \0/

android:launchMode="singleTop"