get the last picture taken by user
// Find the last picture
String[] projection = new String[]{
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.MIME_TYPE
};
final Cursor cursor = getContext().getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
// Put it in the image view
if (cursor.moveToFirst()) {
final ImageView imageView = (ImageView) findViewById(R.id.pictureView);
String imageLocation = cursor.getString(1);
File imageFile = new File(imageLocation);
if (imageFile.exists()) { // TODO: is there a better way to do this?
Bitmap bm = BitmapFactory.decodeFile(imageLocation);
imageView.setImageBitmap(bm);
}
}
I'm still working on the MMS sending part.
Here it is in Kotlin. I have used Glide library to load the last image into an imageview
private fun getLastImageFromGallery(){
val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.Media._ID,
MediaStore.Images.ImageColumns.DATE_ADDED,
MediaStore.Images.ImageColumns.MIME_TYPE
)
val cursor: Cursor = applicationContext.contentResolver.query(uriExternal, projection, null,
null, MediaStore.Images.ImageColumns.DATE_ADDED + " DESC"
)!!
Log.i("Cursor Last", cursor.moveToLast().toString())
if (cursor.moveToFirst()) {
val columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
val imageId: Long = cursor.getLong(columnIndexID)
val imageURI = Uri.withAppendedPath(uriExternal, "" + imageId)
Glide.with(applicationContext)
.load(imageURI)
.transform(CenterCrop(), RoundedCorners(12))
.into(imageView)
}
cursor.close()
}
Inspired by https://stackoverflow.com/a/20065920/763459
So the main concern in that answer was not all the devices are using "DCIM" as the camera folder. Then I found out that if a file is located inside a app-specified folder, it will be indexed by ContentResolver
but the other app doesn't have access to it, which means canRead=false
. So here I come up with another solution:
while (cursor.moveToNext()) {
String imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
File imageFile = new File(imagePath);
if (imageFile.canRead() && imageFile.exists()) {
// we have found the latest picture in the public folder, do whatever you want
break;
}
}