'How to store individual images user selected from gallery?
I am trying to allow user's to upload multiple images from gallery, and the code below does this, but what if I want to access each image that was uploaded and store them inside different variables? I figure I could do something listed below, but I find this to be inefficient, because if the user uploads more than 3 images, then the app crashes due to a null exception.. I would like to be able to allow the user to upload x amount of images, and simply store them all inside individual variables, what would be the best approach of doing this?
//opens gallery to allow user to choose multiple images..
public void openGallery() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for (int i = 0; i < count; i++) {
//Uri imageUri = data.getClipData().getItemAt(i).getUri();
selectedImageUri = data.getClipData().getItemAt(0).getUri();
uriTwo = data.getClipData().getItemAt(1).getUri();
uriThree = data.getClipData().getItemAt(2).getUri();
Log.i("image1", selectedImageUri.toString());
Log.i("image2", uriTwo.toString());
Log.i("image3", uriThree.toString());
Glide
.with(getContext())
.load(selectedImageUri)
.fitCenter()
.into(chosenProductImage);
}
}
} else if (data.getData() != null) {
String imagePath = data.getData().getPath();
Log.i("dataa", imagePath);
//do something with the image (save it to some directory or whatever you need to do with it here)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
