Can't select any image from system image picker - android

So I implemented code to let me pick images from my filesystem using the default image picker in Android, but for some reason every image is greyed out. It's not letting me choose an image at all. I tested it on Marshmallow 6.0.1 (from where screenshot is taken) and on Lollipop 5.1.1.
Here's my implementation:
Manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.company.app.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Note that all of this has been done on the same activity, LaunchActivity.java
Variables as used:
private ImageView picturebutton;
private Bitmap imageBitmap;
final private int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE=1;
private int PICK_IMAGE_REQUEST = 1;
ImageView acting as button:
picturebutton = (ImageView) findViewById(R.id.chose_picture);
View.OnClickListener picturebuttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
checkStorageReadPermission(LaunchActivity.this);
}
};
picturebutton.setOnClickListener(picturebuttonClickListener);
The method checkStorageReadPermission() which requests for storage access permission:
public void checkStorageReadPermission(final Context context){
if(ContextCompat.checkSelfPermission(LaunchActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(LaunchActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)){
}
else {
ActivityCompat.requestPermissions(LaunchActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
}
else{
Log.d("Permissions","Permission was already granted");
startActivity(openGallery());
}
}
The override code for onRequestPermissionsResult():
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startActivity(openGallery());
Log.d("Permissions","Can read storage");
} else {
//code for deny
Log.e("Permissions","Can't read storage");
}
break;
}
}
The intent openGallery() which calls the image picker:
public Intent openGallery() {
Intent og = new Intent();
og.setType("image*/");
og.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
return og;
}
The code to override onActivityResult() when the Intent is called:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(resultCode,requestCode,data);
if(requestCode==PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri imageUri = data.getData();
try{
imageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
x.uploadImage(imageBitmap,LaunchActivity.this);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is no problem with the permission requesting process, the system permission dialog for external storage access comes up, gets granted and the picker opens up, but I can't select any image. Help will be appreciated!

Instead of startActivity(openGallery());,just call openGallery(); method. You are already launching the image picker in that method using startActivityForResilt, so you do not need startActivity() again. Also, remove the return statement from openGallery().
Also, you are setting the MIME type wrong. It should be image/*.
So, the updated one should be:
public void openGallery() {
Intent og = new Intent();
og.setType("image/*");
og.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
}

OnChoose Code
chooseimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23){
boolean result= Utility.checkPermission(getActivity());
if(result) {
galleryIntent();
}
}
else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS
}
}
});
Also Code added For Permission and Set Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= 23) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
onSelectFromGalleryResult(data);
}
}
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Bitmap bitmap = null;
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
}
cursor.close();
}
else {
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
mPath = cursor.getString(cursor.getColumnIndex(filePath[0]));
//edAttach.setText(mPath.toString()); path set anywhere
cursor.close();
}
}
}
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ivprofile.setImageBitmap(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
//edAttach.setText(mPath); path set anywhere
}
cursor.close();
}
else {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPath = cursor.getString(columnIndex).toString();
System.out.println("picturePath" + mPath);
if (!mPath.equalsIgnoreCase(null)) {
edAttach.setText(mPath);
}
cursor.close();
}
}
public boolean hasPermissionInManifest(Context context, String permissionName) {
final String packageName = context.getPackageName();
try {
final PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equals(permissionName)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
galleryIntent();
} else {
//code for deny
}
break;
}
}
Or Permission In your mainfiest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Utility.java
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
}

If you cannot select one of the image in the list I think the problem is on the intent.
The intent openGallery() which calls the image picker:
public Intent openGallery() {
Intent og = new Intent();
og.setType("image*/");
og.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
return og;
}
actually I see that you made a mistake here
og.setType("image*/");
you should write ("image/*") or specify an extension like ("image/jpg") for example!
and actually you don't need for this operation of
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
as the ACTION_GET_CONTENT pick only the image Uri don't need for this permission

Related

Pick image from Gallery - File not found when running newer Android versions

I am working on a address book like Android SDK 14+ app. The users should be able to pick an image from the Gallery to add it to a contact entry.
Running the following code to pick and copy the image is no problem in API 14-20 but does not work in API 21+. The file is not found anymore:
protected void pickFoto() {
if (filePermissionsRequired()) {
askForFilePermissions(new PermissionRequestCompletionHandler() {
#Override
public void onPermissionRequestResult(boolean permissionGranted) {
if (permissionGranted)
addOrEditReceipt();
}
});
return;
}
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent , PICK_FOTO_ACTION);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
...
case PICK_FOTO_ACTION: {
Uri imageUri = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
public interface PermissionRequestCompletionHandler {
void onPermissionRequestResult(boolean permissionGranted);
}
private PermissionRequestCompletionHandler permissionRequestCompletionHandler;
public boolean filePermissionsRequired() {
if (Build.VERSION.SDK_INT >= 23)
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
else
return false;
}
public boolean askForFilePermissions(PermissionRequestCompletionHandler completionHandler) {
if (Build.VERSION.SDK_INT >= 23) {
permissionRequestCompletionHandler = completionHandler;
boolean hasPermission = this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!hasPermission) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return true;
}
}
permissionRequestCompletionHandler = null;
return false;
}
The app has runtime permissions to access the Gallery. So what am I doing wrong? How to access the file on newer API versions?
}
try below code to open the camera and getting result:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + System.currentTimeMillis() + ".png");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICK_FOTO_ACTION);
for getting result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_FOTO_ACTION: {
Uri imageUri = imageUri;
File imgFile = new File(imageUri.getPath());
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
}
for getting actual path from uri :
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
remove unwanted uri part :
public String RemoveUnwantedString(String pathUri){
//pathUri = "content://com.google.android.apps.photos.contentprovider/-1/2/content://media/external/video/media/5213/ORIGINAL/NONE/2106970034"
String[] d1 = pathUri.split("content://");
for (String item1:d1) {
if (item1.contains("media/")) {
String[] d2 = item1.split("/ORIGINAL/");
for (String item2:d2) {
if (item2.contains("media/")) {
pathUri = "content://" + item2;
break;
}
}
break;
}
}
//pathUri = "content://media/external/video/media/5213"
return pathUri;
}
For versions 21 and higher you can do this , you need to add a condition to check the SDK version for this. Exectute this code in the API 21+ condition block.
String wholeID = DocumentsContract.getDocumentId(imageUri );
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
Call the Gallery with belo code
public static final int SELECT_IMAGE_FROM_GALLERY_CODE = 701;
public static void callGallery(Activity activity) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
SELECT_IMAGE_FROM_GALLERY_CODE);
}
In OnActivityResult, read URI and read path from uri.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CommonUtils.SELECT_IMAGE_FROM_GALLERY_CODE) {
if (data != null) {
Uri selectedImageUri = data.getData();
// get path from Uri
String imagepath = getPath(this, selectedImageUri);
if (null != imagepath && (!imagepath.isEmpty())) {
// if the image path is not null and not empty, copy image to sdcard
try {
copyDirectoryOrFile(new File(imagepath), new File(myTargetImageFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// load the image into imageView with the help og glide.
loadImageWithGlide(myImageViewContactImage,
myTargetImageFilePath, myDefaultImagePath, myErrorImagePath, false);
} else {
Toast.makeText(this, "Error: Photo selection failed.", Toast.LENGTH_LONG).show();
}
}
}
}
public void loadImageWithGlide(ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int theErrorImagePath,
boolean theIsSkipMemoryCache) {
if (theIsSkipMemoryCache) {
Glide.with(ProfileActivity.this) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(theErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.centerCrop()
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
} else {
Glide.with(ProfileActivity.this)
.load(theLoadImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.centerCrop()
.into(theImageViewToLoadImage);
}
}
public static String getPath(Context theCtx, Uri uri) {
try {
Cursor cursor = (theCtx).getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = (theCtx).getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
} catch (Exception e) {
return null;
}
}
public static void copyDirectoryOrFile(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectoryOrFile(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create directory " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To load image with glide, add following dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'

Can't load Image into an ImageView

I'm having a problem loading an image from the gallery in my Android app. I have some code that picks an image in emulator. When I make a selection, an exception is thrown and caught, meaning the image doesn't load, but I'm not sure how to diagnose what's happening.
Here is my java code file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
galleryImage = (ImageView) findViewById(R.id.imageView);
pick_btn = (Button)findViewById(R.id.button);
pick_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,RESULT_LOAD_IMG);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
Log.i("Image Column Index..", "hoiiii");
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
galleryImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}catch (Exception e)
{
Toast.makeText(getApplicationContext(),"You haven't picked any image",Toast.LENGTH_LONG).show();
}
}
}
You need to ask runtime permission for WRITE_EXTERNAL_STORAGE before
you pick image from gallary.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
declare permissions and request code
private static final String[] REQUEST_PERMISSIONS = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final int REQUEST_PERMISSION_CODE = 007;
//check if permissions are needed
if (!checkPermission()) {
requestPermission();
} else {
//open gallary and pick image
}
private boolean checkPermission () {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
for (String permission : REQUEST_PERMISSIONS) {
if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
private void requestPermission () {
ActivityCompat.requestPermissions(this, REQUEST_PERMISSIONS, REQUEST_PERMISSION_CODE);
}
#Override
public void onRequestPermissionsResult ( int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults){
if (requestCode == REQUEST_PERMISSION_CODE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//open gallary and pick image
}
}
}
please check user-permission in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my edited code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (!Settings.System.canWrite(this) && (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data))
{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 2909);
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
} catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}

Storing image to internal storage

I want to store my images to internal storage, I searched google and stackoverflow but couldn't get it done, Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = (ImageView) findViewById(R.id.ss);
tv = (TextView) findViewById(R.id.tv);
// Firebase.setAndroidContext(this);
//Firebase ref = new Firebase(FIREBASE_URL);
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeResource(getResources(),
RESULT_LOAD_IMAGE);
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/Save Image Tutorial/");
dir.mkdirs();
// Create a name for the saved image
File file = new File(dir, "myimage.png");
// Show a toast message on successful save
Toast.makeText(MainActivity.this, "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// drawView.load_pic(picturePath);
}
}
I want to get an image from the gallery and store it to internal storage but in this code, it is only saving the name of the file in the directory. If someone could help me to solve this.
You could use FileOutputStream to store your bitmap. After getting the bitmap from gallery, FileOutputStream out = null;
try {
out = new FileOutputStream("fileName"); //Enter the desired filename
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
you are writing Image file on external storage
File filepath = Environment.getExternalStorageDirectory();
so check that you have mention proper permission in android manifest to write data on SD card
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and also get the bitmap from selected path
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
instead of
bitmap = BitmapFactory.decodeResource(getResources(),
RESULT_LOAD_IMAGE);
RESULT_LOAD_IMAGE is request code not resource id of selected image
OnChoose Code
chooseimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23){
boolean result= Utility.checkPermission(getActivity());
if(result) {
galleryIntent();
}
}
else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS
}
}
});
Also Runtime permission added and Set image on your desired location
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= 23) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
onSelectFromGalleryResult(data);
}
}
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Bitmap bitmap = null;
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
}
cursor.close();
}
else {
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
mPath = cursor.getString(cursor.getColumnIndex(filePath[0]));
//edAttach.setText(mPath.toString()); path set anywhere
cursor.close();
}
}
}
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bitmap=null;
if (data != null) {
try {
bitmap= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ivprofile.setImageBitmap(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
//edAttach.setText(mPath); path set anywhere
}
cursor.close();
}
else {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPath = cursor.getString(columnIndex).toString();
System.out.println("picturePath" + mPath);
if (!mPath.equalsIgnoreCase(null)) {
edAttach.setText(mPath);
}
cursor.close();
}
// Your Image Copy on Your desired location
if(!mPath.equalsIgnoreCase(""))
{
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/"+"Save Image Tutorial"+"/");
dir.mkdirs();
// Create a name for the saved image
File file = new File(dir, "myImage.png");
// Show a toast message on successful save
try {
FileOutputStream output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
Toast.makeText(getActivity(), "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean hasPermissionInManifest(Context context, String permissionName) {
final String packageName = context.getPackageName();
try {
final PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equals(permissionName)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
galleryIntent();
} else {
//code for deny
}
break;
}
}
Or Permission In your mainfiest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Utility.java
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
}

select multiple images from gallery using startActivityResult [duplicate]

So basically what i am trying to achieve is opening the Gallery in Android and let the user select multiple images. Now this question has been asked frequently but i'm not satisfied with the answers. Mainly because i found something interesting in de docs in my IDE (i come back on this later) and thereby i don't want to use a custom adapter but just the vanilla one.
Now my code for selecting one image is:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
Now People on SO and other websites wil tell you you have 2 options:
1) Do not use ACTION_GET_CONTENT but ACTION_SEND_MULTIPLE instead.
This one doesn't work. This one is according to the docs for sending files and not retrieving and that's exactly what it does. When using ACTION_SEND_MULTIPLE i got a window opened at my device where i have to select an application to send my data to. That's not what i want, so i wonder how people got this achieved with this solution.. Do i miss something?
2) Implement an custom Gallery. Now this is my last option i will consider because imho it's not what i am searching for because i have to style it myself AND why the heck you just can't select multiple images in the vanilla gallery?
There must be an option for this.. Now the interesting thing what i'v found is this:
I found this in the docs description of ACTION_GET_CONTENT.
If the caller can handle multiple returned items (the user performing
multiple selection), then it can specify EXTRA_ALLOW_MULTIPLE to
indicate this.
This is pretty interesting. Here they are referring it to the use case where a user can select multiple items?
Later on they say in the docs:
You may use EXTRA_ALLOW_MULTIPLE to allow the user to select multiple
items.
So this is pretty obvious right? This is what i need. But my following question is: Where can i put this EXTRA_ALLOW_MULTIPLE? The sad thing is that i can't find this no where in the developers.android guide and also is this not defined as a constant in the INTENT class.
Anybody can help me out with this EXTRA_ALLOW_MULTIPLE?
The EXTRA_ALLOW_MULTIPLE option is set on the intent through the Intent.putExtra() method:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Your code above should look like this:
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
Note: the EXTRA_ALLOW_MULTIPLE option is only available in Android API 18 and higher.
Define these variables in the class:
int PICK_IMAGE_MULTIPLE = 1;
String imageEncoded;
List<String> imagesEncodedList;
Let's Assume that onClick on a button it should open gallery to select images
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
Then you should override onActivityResult Method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
NOTE THAT:
the gallery doesn't give you the ability to select multi-images so we here open all images studio that you can select multi-images from them.
and don't forget to add the permissions to your manifest
VERY IMPORTANT:
getData(); to get one single image and I've stored it here in imageEncoded String
if the user select multi-images then
they should be stored in the list
So you have to check which is null to use the other
Wish you have a nice try and to others
A lot of these answers have similarities but are all missing the most important part which is in onActivityResult, check if data.getClipData is null before checking data.getData
The code to call the file chooser:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*"); //allows any image file type. Change * to specific extension to limit it
//**The following line is the important one!
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURES); //SELECT_PICTURES is simply a global int used to check the calling intent in onActivityResult
The code to get all of the images selected:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SELECT_PICTURES) {
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();
//do something with the image (save it to some directory or whatever you need to do with it here)
}
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//do something with the image (save it to some directory or whatever you need to do with it here)
}
}
}
Note that Android's chooser has Photos and Gallery available on some devices. Photos allows multiple images to be selected. Gallery allows just one at a time.
I hope this answer isn't late. Because the gallery widget doesn't support multiple selection by default, but you can custom the gridview which accepted your multiselect intent. The other option is to extend the gallery view and add in your own code to allow multiple selection.
This is the simple library can do it: https://github.com/luminousman/MultipleImagePick
Update:
From #ilsy's comment, CustomGalleryActivity in this library use manageQuery, which is deprecated, so it should be changed to getContentResolver().query() and cursor.close() like this answer
Initialize instance:
private String imagePath;
private List<String> imagePathList;
In onActivityResult You have to write this, If-else 2 block. One for single image and another for multiple image.
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && data != null) {
imagePathList = new ArrayList<>();
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for (int i=0; i<count; i++) {
Uri imageUri = data.getClipData().getItemAt(i).getUri();
getImageFilePath(imageUri);
}
}
else if (data.getData() != null) {
Uri imgUri = data.getData();
getImageFilePath(imgUri);
}
}
Most important part, Get Image Path from uri:
public void getImageFilePath(Uri uri) {
File file = new File(uri.getPath());
String[] filePath = file.getPath().split(":");
String image_id = filePath[filePath.length - 1];
Cursor cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
if (cursor!=null) {
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
imagePathList.add(imagePath);
cursor.close();
}
}
Hope this can help you.
2022 - The Android Jetpack Compose way
For selecting multiple images in the gallery with Android Jetpack Compose.
val launcherMultipleImages = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetMultipleContents(),
) { uriList: List<Uri> ->
// TODO
}
And then use launcherMultipleImages.launch("image/*") to start the images selection.
For example :
Button(onClick = { launcherMultipleImages.launch("image/*") }) {
Text(text = "Select images")
}
this works for multiple image selection. also tested in API 29,30 in Google photos.
private static final int PICK_IMAGE = 2;
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select
images"),PICK_IMAGE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for(int i = 0; i < count; i++) {
Uri imageUri = data.getClipData().getItemAt(i).getUri();
//do what do you want to do
}
}
else if(data.getData() != null) {
Uri selectedImageUri = data.getData();
//do what do you want to do
}
}
Define getContent as below;
val getContent =
registerForActivityResult(ActivityResultContracts.GetMultipleContents())
{ uriList ->
// todo
}
after you grant related permission run the below code
getContent.launch("images/*")
I got null from the Cursor.
Then found a solution to convert the Uri into Bitmap that works perfectly.
Here is the solution that works for me:
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
{
if (resultCode == Activity.RESULT_OK) {
if (requestCode == YOUR_REQUEST_CODE) {
if (data != null) {
if (data.getData() != null) {
Uri contentURI = data.getData();
ex_one.setImageURI(contentURI);
Log.d(TAG, "onActivityResult: " + contentURI.toString());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), contentURI);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
Hi below code is working fine.
Cursor imagecursor1 = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
imageUrls.size();
for (int i = 0; i < imagecursor1.getCount(); i++) {
imagecursor1.moveToPosition(i);
int dataColumnIndex = imagecursor1
.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor1.getString(dataColumnIndex));
}
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory().cacheOnDisc().build();
imageAdapter = new ImageAdapter(this, imageUrls);
gridView = (GridView) findViewById(R.id.PhoneImageGrid);
gridView.setAdapter(imageAdapter);
You want to more clarifications.
http://mylearnandroid.blogspot.in/2014/02/multiple-choose-custom-gallery.html
I also had the same issue. I also wanted so users could take photos easily while picking photos from the gallery. Couldn't find a native way of doing this therefore I decided to make an opensource project. It is much like MultipleImagePick but just better way of implementing it.
https://github.com/giljulio/android-multiple-image-picker
private static final RESULT_CODE_PICKER_IMAGES = 9000;
Intent intent = new Intent(this, SmartImagePicker.class);
startActivityForResult(intent, RESULT_CODE_PICKER_IMAGES);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case RESULT_CODE_PICKER_IMAGES:
if(resultCode == Activity.RESULT_OK){
Parcelable[] parcelableUris = data.getParcelableArrayExtra(ImagePickerActivity.TAG_IMAGE_URI);
//Java doesn't allow array casting, this is a little hack
Uri[] uris = new Uri[parcelableUris.length];
System.arraycopy(parcelableUris, 0, uris, 0, parcelableUris.length);
//Do something with the uris array
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
Try this one IntentChooser. Just add some lines of code, I did the rest for you.
private void startImageChooserActivity() {
Intent intent = ImageChooserMaker.newChooser(MainActivity.this)
.add(new ImageChooser(true))
.create("Select Image");
startActivityForResult(intent, REQUEST_IMAGE_CHOOSER);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CHOOSER && resultCode == RESULT_OK) {
List<Uri> imageUris = ImageChooserMaker.getPickMultipleImageResultUris(this, data);
}
}
PS: as mentioned at the answers above, EXTRA_ALLOW_MULTIPLE is only available for API >= 18. And some gallery apps don't make this feature available (Google Photos and Documents (com.android.documentsui) work.
// for choosing multiple images declare variables
int PICK_IMAGE_MULTIPLE = 2;
String realImagePath;
// After requesting FILE READ PERMISSION may be on button click
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Images"), PICK_IMAGE_MULTIPLE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);// FOR CHOOSING MULTIPLE IMAGES
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
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();
realImagePath = getPath(this, imageUri);
//do something with the image (save it to some directory or whatever you need to do with it here)
Log.e("ImagePath", "onActivityResult: " + realImagePath);
}
} else if (data.getData() != null) {
Uri imageUri = data.getData();
realImagePath = getPath(this, imageUri);
//do something with the image (save it to some directory or whatever you need to do with it here)
Log.e("ImagePath", "onActivityResult: " + realImagePath);
}
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public static String getPath(final Context context, final Uri uri) {
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.parseLong(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
this worked perfectly for me credits: Get real path from URI, Android KitKat new storage access framework
For selecting multiple image from gallery
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
An Ultimate Solution for multiple image upload with camera option also for Android Lollipop to Android 10, SDK 30.
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadMessages;
private Uri mCapturedImageURI = null;
Add this to OnCreate of MainActivity
mWebView.setWebChromeClient(new WebChromeClient() {
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
mUploadMessage = uploadMsg;
openImageChooser();
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadMessages = filePathCallback;
openImageChooser();
return true;
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg){
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
private void openImageChooser() {
try {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "FolderName");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mCapturedImageURI = Uri.fromFile(file);
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
onActivityResult
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage && null == mUploadMessages) {
return;
}
if (null != mUploadMessage) {
handleUploadMessage(requestCode, resultCode, data);
} else if (mUploadMessages != null) {
handleUploadMessages(requestCode, resultCode, data);
}
}
}
private void handleUploadMessage(final int requestCode, final int resultCode, final Intent data) {
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
e.printStackTrace();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} // end of code for all versions except of Lollipop
private void handleUploadMessages(final int requestCode, final int resultCode, final Intent data) {
Uri[] results = null;
try {
if (resultCode != RESULT_OK) {
results = null;
} else {
if (data != null) {
String dataString = data.getDataString();
ClipData clipData = data.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
} else {
results = new Uri[]{mCapturedImageURI};
}
}
} catch (Exception e) {
e.printStackTrace();
}
mUploadMessages.onReceiveValue(results);
mUploadMessages = null;
}
For Multiple image selection and with selection limit restriction feature, use chintan369/MultiImagePicker library which is the latest of 2021 and supports Android 11 too. It is well documented and also demo is explained on youtube for use. It's very easy to add in the project, easy to use to call the library for image selection and getting results of selected images as Uri list and also you can request result list as absolute file path list.

Select multiple images from android gallery

So basically what i am trying to achieve is opening the Gallery in Android and let the user select multiple images. Now this question has been asked frequently but i'm not satisfied with the answers. Mainly because i found something interesting in de docs in my IDE (i come back on this later) and thereby i don't want to use a custom adapter but just the vanilla one.
Now my code for selecting one image is:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
Now People on SO and other websites wil tell you you have 2 options:
1) Do not use ACTION_GET_CONTENT but ACTION_SEND_MULTIPLE instead.
This one doesn't work. This one is according to the docs for sending files and not retrieving and that's exactly what it does. When using ACTION_SEND_MULTIPLE i got a window opened at my device where i have to select an application to send my data to. That's not what i want, so i wonder how people got this achieved with this solution.. Do i miss something?
2) Implement an custom Gallery. Now this is my last option i will consider because imho it's not what i am searching for because i have to style it myself AND why the heck you just can't select multiple images in the vanilla gallery?
There must be an option for this.. Now the interesting thing what i'v found is this:
I found this in the docs description of ACTION_GET_CONTENT.
If the caller can handle multiple returned items (the user performing
multiple selection), then it can specify EXTRA_ALLOW_MULTIPLE to
indicate this.
This is pretty interesting. Here they are referring it to the use case where a user can select multiple items?
Later on they say in the docs:
You may use EXTRA_ALLOW_MULTIPLE to allow the user to select multiple
items.
So this is pretty obvious right? This is what i need. But my following question is: Where can i put this EXTRA_ALLOW_MULTIPLE? The sad thing is that i can't find this no where in the developers.android guide and also is this not defined as a constant in the INTENT class.
Anybody can help me out with this EXTRA_ALLOW_MULTIPLE?
The EXTRA_ALLOW_MULTIPLE option is set on the intent through the Intent.putExtra() method:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Your code above should look like this:
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);
Note: the EXTRA_ALLOW_MULTIPLE option is only available in Android API 18 and higher.
Define these variables in the class:
int PICK_IMAGE_MULTIPLE = 1;
String imageEncoded;
List<String> imagesEncodedList;
Let's Assume that onClick on a button it should open gallery to select images
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
Then you should override onActivityResult Method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
NOTE THAT:
the gallery doesn't give you the ability to select multi-images so we here open all images studio that you can select multi-images from them.
and don't forget to add the permissions to your manifest
VERY IMPORTANT:
getData(); to get one single image and I've stored it here in imageEncoded String
if the user select multi-images then
they should be stored in the list
So you have to check which is null to use the other
Wish you have a nice try and to others
A lot of these answers have similarities but are all missing the most important part which is in onActivityResult, check if data.getClipData is null before checking data.getData
The code to call the file chooser:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*"); //allows any image file type. Change * to specific extension to limit it
//**The following line is the important one!
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURES); //SELECT_PICTURES is simply a global int used to check the calling intent in onActivityResult
The code to get all of the images selected:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SELECT_PICTURES) {
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();
//do something with the image (save it to some directory or whatever you need to do with it here)
}
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//do something with the image (save it to some directory or whatever you need to do with it here)
}
}
}
Note that Android's chooser has Photos and Gallery available on some devices. Photos allows multiple images to be selected. Gallery allows just one at a time.
I hope this answer isn't late. Because the gallery widget doesn't support multiple selection by default, but you can custom the gridview which accepted your multiselect intent. The other option is to extend the gallery view and add in your own code to allow multiple selection.
This is the simple library can do it: https://github.com/luminousman/MultipleImagePick
Update:
From #ilsy's comment, CustomGalleryActivity in this library use manageQuery, which is deprecated, so it should be changed to getContentResolver().query() and cursor.close() like this answer
Initialize instance:
private String imagePath;
private List<String> imagePathList;
In onActivityResult You have to write this, If-else 2 block. One for single image and another for multiple image.
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && data != null) {
imagePathList = new ArrayList<>();
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for (int i=0; i<count; i++) {
Uri imageUri = data.getClipData().getItemAt(i).getUri();
getImageFilePath(imageUri);
}
}
else if (data.getData() != null) {
Uri imgUri = data.getData();
getImageFilePath(imgUri);
}
}
Most important part, Get Image Path from uri:
public void getImageFilePath(Uri uri) {
File file = new File(uri.getPath());
String[] filePath = file.getPath().split(":");
String image_id = filePath[filePath.length - 1];
Cursor cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
if (cursor!=null) {
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
imagePathList.add(imagePath);
cursor.close();
}
}
Hope this can help you.
2022 - The Android Jetpack Compose way
For selecting multiple images in the gallery with Android Jetpack Compose.
val launcherMultipleImages = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetMultipleContents(),
) { uriList: List<Uri> ->
// TODO
}
And then use launcherMultipleImages.launch("image/*") to start the images selection.
For example :
Button(onClick = { launcherMultipleImages.launch("image/*") }) {
Text(text = "Select images")
}
this works for multiple image selection. also tested in API 29,30 in Google photos.
private static final int PICK_IMAGE = 2;
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select
images"),PICK_IMAGE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for(int i = 0; i < count; i++) {
Uri imageUri = data.getClipData().getItemAt(i).getUri();
//do what do you want to do
}
}
else if(data.getData() != null) {
Uri selectedImageUri = data.getData();
//do what do you want to do
}
}
Define getContent as below;
val getContent =
registerForActivityResult(ActivityResultContracts.GetMultipleContents())
{ uriList ->
// todo
}
after you grant related permission run the below code
getContent.launch("images/*")
I got null from the Cursor.
Then found a solution to convert the Uri into Bitmap that works perfectly.
Here is the solution that works for me:
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
{
if (resultCode == Activity.RESULT_OK) {
if (requestCode == YOUR_REQUEST_CODE) {
if (data != null) {
if (data.getData() != null) {
Uri contentURI = data.getData();
ex_one.setImageURI(contentURI);
Log.d(TAG, "onActivityResult: " + contentURI.toString());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), contentURI);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
Hi below code is working fine.
Cursor imagecursor1 = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
imageUrls.size();
for (int i = 0; i < imagecursor1.getCount(); i++) {
imagecursor1.moveToPosition(i);
int dataColumnIndex = imagecursor1
.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor1.getString(dataColumnIndex));
}
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory().cacheOnDisc().build();
imageAdapter = new ImageAdapter(this, imageUrls);
gridView = (GridView) findViewById(R.id.PhoneImageGrid);
gridView.setAdapter(imageAdapter);
You want to more clarifications.
http://mylearnandroid.blogspot.in/2014/02/multiple-choose-custom-gallery.html
I also had the same issue. I also wanted so users could take photos easily while picking photos from the gallery. Couldn't find a native way of doing this therefore I decided to make an opensource project. It is much like MultipleImagePick but just better way of implementing it.
https://github.com/giljulio/android-multiple-image-picker
private static final RESULT_CODE_PICKER_IMAGES = 9000;
Intent intent = new Intent(this, SmartImagePicker.class);
startActivityForResult(intent, RESULT_CODE_PICKER_IMAGES);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case RESULT_CODE_PICKER_IMAGES:
if(resultCode == Activity.RESULT_OK){
Parcelable[] parcelableUris = data.getParcelableArrayExtra(ImagePickerActivity.TAG_IMAGE_URI);
//Java doesn't allow array casting, this is a little hack
Uri[] uris = new Uri[parcelableUris.length];
System.arraycopy(parcelableUris, 0, uris, 0, parcelableUris.length);
//Do something with the uris array
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
Try this one IntentChooser. Just add some lines of code, I did the rest for you.
private void startImageChooserActivity() {
Intent intent = ImageChooserMaker.newChooser(MainActivity.this)
.add(new ImageChooser(true))
.create("Select Image");
startActivityForResult(intent, REQUEST_IMAGE_CHOOSER);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CHOOSER && resultCode == RESULT_OK) {
List<Uri> imageUris = ImageChooserMaker.getPickMultipleImageResultUris(this, data);
}
}
PS: as mentioned at the answers above, EXTRA_ALLOW_MULTIPLE is only available for API >= 18. And some gallery apps don't make this feature available (Google Photos and Documents (com.android.documentsui) work.
// for choosing multiple images declare variables
int PICK_IMAGE_MULTIPLE = 2;
String realImagePath;
// After requesting FILE READ PERMISSION may be on button click
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Images"), PICK_IMAGE_MULTIPLE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);// FOR CHOOSING MULTIPLE IMAGES
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
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();
realImagePath = getPath(this, imageUri);
//do something with the image (save it to some directory or whatever you need to do with it here)
Log.e("ImagePath", "onActivityResult: " + realImagePath);
}
} else if (data.getData() != null) {
Uri imageUri = data.getData();
realImagePath = getPath(this, imageUri);
//do something with the image (save it to some directory or whatever you need to do with it here)
Log.e("ImagePath", "onActivityResult: " + realImagePath);
}
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public static String getPath(final Context context, final Uri uri) {
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.parseLong(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
this worked perfectly for me credits: Get real path from URI, Android KitKat new storage access framework
For selecting multiple image from gallery
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
An Ultimate Solution for multiple image upload with camera option also for Android Lollipop to Android 10, SDK 30.
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadMessages;
private Uri mCapturedImageURI = null;
Add this to OnCreate of MainActivity
mWebView.setWebChromeClient(new WebChromeClient() {
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
mUploadMessage = uploadMsg;
openImageChooser();
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadMessages = filePathCallback;
openImageChooser();
return true;
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg){
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
private void openImageChooser() {
try {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "FolderName");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mCapturedImageURI = Uri.fromFile(file);
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
onActivityResult
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage && null == mUploadMessages) {
return;
}
if (null != mUploadMessage) {
handleUploadMessage(requestCode, resultCode, data);
} else if (mUploadMessages != null) {
handleUploadMessages(requestCode, resultCode, data);
}
}
}
private void handleUploadMessage(final int requestCode, final int resultCode, final Intent data) {
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
e.printStackTrace();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} // end of code for all versions except of Lollipop
private void handleUploadMessages(final int requestCode, final int resultCode, final Intent data) {
Uri[] results = null;
try {
if (resultCode != RESULT_OK) {
results = null;
} else {
if (data != null) {
String dataString = data.getDataString();
ClipData clipData = data.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
} else {
results = new Uri[]{mCapturedImageURI};
}
}
} catch (Exception e) {
e.printStackTrace();
}
mUploadMessages.onReceiveValue(results);
mUploadMessages = null;
}
For Multiple image selection and with selection limit restriction feature, use chintan369/MultiImagePicker library which is the latest of 2021 and supports Android 11 too. It is well documented and also demo is explained on youtube for use. It's very easy to add in the project, easy to use to call the library for image selection and getting results of selected images as Uri list and also you can request result list as absolute file path list.

Categories

Resources