OnActivityResult gets RESULT_CANCELLED when using Intent.EXTRA_ALLOW_MULTIPLE

I have the following button in my activity, which opens the gallery to select one or more images, and below is the OnActivityResult function, which returns the result as RESULT_CANCELLED for several images and RESULT_OK for one image. I don’t know why this is happening. Maybe someone can help.

 buttonGallery.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent,"Select Picture"), choose_picture); //startActivity(intent); } }); //OnActivityResult for the above public void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == choose_picture) { Uri imageUri = (Uri)data.getParcelableExtra(Intent.EXTRA_STREAM); //Do something } 

I get data.getData() as null , data.getExtras() as null .

Can anyone help me get the required results from the above code. I want the URIs all the images that the user selects from the gallery.

PS: It works fine for a single image, I don’t know why.

+8
android android-intent
source share
1 answer

Finally, I got a solution. When using EXTRA_ALLOW_MULTIPLE , when there is more than one content that the user selects, instead of returning to intent.getExtra() , the data from the intention is returned to ClipData , which is only supported for SDK versions 18 and higher. From there, the data can be obtained using the following code β†’

  if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) && (null == data.getData())) { ClipData clipdata = data.getClipData(); for (int i=0; i<clipdata.getItemCount();i++) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), clipdata.getItemAt(i).getUri()); //DO something } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

I put a null check for intent.getData() , because in the case of a single image, data is accepted in intent.getData() , and in the case of multiple selection, it is taken as null .

So, for sdk versions below 18 and for a single selection (regardless of sdk version) the data can simply be obtained as follows:

 InputStream ist = this.getContentResolver() .openInputStream(data.getData()); Bitmap bitmap = BitmapFactory.decodeStream(ist); 
+18
source share

All Articles