Android not getting right photo from gallery - android

I am implementing a pick photo from gallery and then show it in a ImageView. I had the some issues and, thanks to this solution: Null Intent passed back on Samsung, is partially solved. I can take the photo and it's saved in a custom location:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Helpers.isExternalStorageWritable()) {
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), Globals.Constants.APP_NAME);
imagesFolder.mkdirs();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date());
File image = new File(imagesFolder, "report" + timeStamp + ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
getActivity().startActivityForResult(imageIntent, CAMERA_REQUEST);
However when in onActivityResult, when I show the taken picture in a ImageView, I got a random photo from my old photos. Here's my onActivityResult code:
try {
Log.i("TAG", "inside Samsung Phones");
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA };
String selection = MediaStore.Images.Thumbnails.KIND + "=" + MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
Cursor myCursor = getActivity().getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, selection, null, sort);
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
myCursor.moveToFirst();
imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
// myCursor.close();
}
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
myCursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
mImageCaptureUri_samsung = Uri.fromFile(new File(largeImagePath));
mImageCaptureUri = null;
} finally {
// myCursor.close();
}
Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId));
Uri uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, String.valueOf(thumbnailImageId));
image1.setImageURI(uriThumbnailImage);
}
Another issue is that the .thumbnail neither the actual photo are shown right away, it takes a couple minutes to be shown in the gallery or file manager. But now I would be happy if anyone can help me with the random picture shown. Thank you in advanced!

Related

How we can get Image from Sdcard which have unique name based on timestamp in Android

I know how to retrieve image from sdcard but i can't find solution of retrieving specific image which contains unique timestamp with its name.
How can i get image from sdcard which has unique timestamp while i storing into External directory.?
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//folder stuff
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
Uri uriSavedImage = Uri.fromFile(image);
How can i retrieve above image from sdcard?
This below code is to retrieve the files from the folder with filename start with "QR_[eight int '-' six int]"
private void getFiles() {
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
String path = imagesFolder.getAbsolutePath();
final String where = MediaStore.Images.Media.DATA + " like ? ";
final String[] args = new String[]{path + File.separator + "QR_" + "%"};
final String[] columns = {MediaStore.Images.Media.DATA};
final Cursor cursor = getActivity().getContentResolver().query(uri, columns, where, args, null);
final String pattern = Pattern.quote(path) + "/[^/]*";
if (cursor != null && cursor.moveToFirst()) {
do {
final String curPath = cursor.getString(0);
if (curPath.matches(pattern)) {
final File file = new File(curPath);
if(file.getName().matches("\\d{8}-\\d{6}")) {
// your file
}
}
} while (cursor.moveToNext());
cursor.close();
}
}

How do I get the album art of the song currently playing

I want to be able to get the album art of the song that is currently playing. I am able to get the name, album, artist with the use of
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
Log.v("tag ", action + " / " + cmd);
String artist = intent.getStringExtra("artist");
String album = intent.getStringExtra("album");
String track = intent.getStringExtra("track");
Log.v("tag", artist + ":" + album + ":" + track);
Fullname = (artist + ":" + album + ":" + track);
Toast.makeText(MusicPlayer.this, track, Toast.LENGTH_SHORT).show();
update();
However, this does not help me with getting album art. Most of the posts on here that ask for getting album art call for the use of
MediaStore.Audio.AlbumColumns.AlbumArt
But I can't seem to figure out how to work it. When I tried to use
Cursor cursor = getActivity().managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID+ "=?",
new String[] {String.valueOf(albumId)},
null);
if (cursor.moveToFirst()) {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
// do whatever you need to do
}
(From here ) or anything similar to this I keep running into the problem of not having a albumId. I read that I should set albumid to
album_id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))
but I can't seem to get a Long without having another cursor which I can't figure out how to do to without the use of a pre-existing albumid. Any help would be greatly appreciated.
I had the same problem. The intent only has the media id. So we have to get the album id related to that media file.
Here's the solution I used :
//get the song's id from intent
long songId = intent.getLongExtra("id", -1);
//get the albumid using media/song id
if(songId!=-1) {
String selection = MediaStore.Audio.Media._ID + " = "+songId+"";
Cursor cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] {
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID},
selection, null, null);
if (cursor.moveToFirst()) {
long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
Log.d("Album ID : ", ""+albumId);
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
//set the album art in imageview
albumArt.setImageURI(albumArtUri);
}
cursor.close();
}
Get Album ID of current playing song and call following function to get Album Art :
public static Bitmap getAlbumart(Context context,Long album_id){
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
try{
final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if (pfd != null){
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
pfd = null;
fd = null;
}
} catch(Error ee){}
catch (Exception e) {}
return bm;
}

Intent ACTION_IMAGE_CAPTURE - how to delete duplicated thumbnail?

After taking a photo by using intent ACTION_IMAGE_CAPTURE with given location to save photo on some devices (my test device is Sony Ericsson Mt11i with android 2.3) default camera app is saving a duplicate image in camera photos folder.
So my app checks if the photo is duplicated and deletes it. But the camera app also saving the thumbnail for taken photo, so i'm deleting it too, but even after I delete this thumbnail there is somewhere still information about this thumbnail, and in device's gallery app image is still present with default image. If I check details of this image there is still information of this photo (date,location). These are my methods for handling duplicated photo:
public static void handleTakenPicture(Context context, int lastId, File tempFile) {
/*
* Checking for duplicate images
* This is necessary because some camera implementation not only save where you want them to save but also in their default location.
*/
if (lastId == 0)
return;
final String[] projection = {MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.SIZE, MediaStore.Images.ImageColumns._ID};
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
final String imageWhere = MediaStore.Images.Media._ID + ">?";
final String[] imageArguments = {Integer.toString(lastId)};
Cursor imageCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, imageWhere, imageArguments,
imageOrderBy);
// List<File> cameraTakenMediaFiles = new ArrayList<File>();
File gFile = null;
if (imageCursor.getCount() > 0) {
// while( imageCursor.moveToNext() ) {
imageCursor.moveToFirst();
// int id =
// imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
String path = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
gFile = new File(path);
// Long takenTimeStamp =
// imageCursor.getLong(imageCursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));
// Long size =
// imageCursor.getLong(imageCursor.getColumnIndex(MediaStore.Images.Media.SIZE));
// cameraTakenMediaFiles.add(new File(path));
//}
}
imageCursor.close();
//File imageFile = new File(imageFilePath);
if (!tempFile.exists() && gFile != null) {
// was not saved where I wanted, but the camera saved one in the media folder
// try to copy over the one saved by the camera and then delete
try {
Prefsy.copyFile(gFile, tempFile);
gFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
if(gFile != null)
{
gFile.delete();
try { // DELETING THUMBNAIL
Cursor th = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Images.ImageColumns.DATA},
MediaStore.Images.Thumbnails.IMAGE_ID + " = ?", new String[] {"" + lastId}, MediaStore.Images.Thumbnails._ID + " DESC");
L(th.getCount()+"");
if (th.getCount() > 0)
{
th.moveToFirst();
L(th.getString(0));
L(new File(th.getString(0)).delete()+"");
L(context.getContentResolver().delete(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
MediaStore.Images.Thumbnails.IMAGE_ID + " = ?", new String[] {"" + lastId})+"");
}
th.close();
} catch (Exception e) {
}
}
/*for( File cameraTakenFile : cameraTakenMediaFiles ) {
// delete the one duplicated
cameraTakenFile.delete();
}*/
}
public static int getLastImageId(Context context){
final String[] imageColumns = { MediaStore.Images.Media._ID };
final String imageOrderBy = MediaStore.Images.Media._ID+" DESC";
final String imageWhere = null;
final String[] imageArguments = null;
Cursor imageCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, imageWhere, imageArguments, imageOrderBy);
if(imageCursor.moveToFirst()){
int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
imageCursor.close();
return id;
}else{
return 0;
}
}
L() is Log method

How to get the path of the image downloaded from third party application and stored in sd card

I am trying to open the gallery and select the image from there.I got the path of all the image which are captured from camera but cannot get the real path of the image which were downloaded from Facebook/picassa etc.The path it is giving is like https://lh3.googleusercontent.com/XNzSBp0MycQ/TigFxMIWn2I/AAAAAAAAAAg/YJPWAWmGOy0/I/11%252520-%2525201.jpg even though it is in gallery.
Here is my code ::
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_IMAGE);
i am using the following code to get the path
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
public String getPath(Uri uri) {
int columnIndex = 0;
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(columnIndex);
return imagePath;
} else {
return null;
}
String filename = "image.jpg";
String path = "/mnt/sdcard/" + filename;
File f = new File(path); //
Uri imageUri = Uri.fromFile(f);

Android get images from sdcard

I am using a code which is listing all the images from my device...and I'm trying to figure it out how to get images only from a specific folder, not all the images. Here is the code I'm using :
ArrayList<Bitmap> images = new ArrayList<Bitmap>();
String[] projection = {MediaStore.Images.Thumbnails.DATA};
Uri uri = Uri.parse("content://media/external/images/media");
cursor = managedQuery( uri, projection, null, null, null);
//cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
Log.i("MediaStore.Images.Media.EXTERNAL_CONTENT_URI", "MediaStore.Images.Media.EXTERNAL_CONTENT_URI: " + MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if(cursor.getCount()==0){
Log.i("No Cards","No Cards");
cursor.close();
} else if(cursor.getCount()>0){
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()){
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String imagePath = cursor.getString(columnIndex);
Log.i("imagePath", "imagePath: " + imagePath);
Bitmap b = BitmapFactory.decodeFile("/Stampii" + imagePath, null);
images.add(b);
}
}
The thing that I want to do is to get images from imagePath: /mnt/sdcard/Stampii/MediaCategory-251.jpg Stampii folder, but I can't understand how to enter the right path to that folder. I've already tried with :
Uri uri = Uri.parse("content://media/external/images/media/mnt/sdcard/Stampii");
Any solutions?
use
File file = new File(Environment.getExternalStoragePath()+"/Stampii/");
file imageList[] = file.listFiles();
for(int i=0;i<imageList.length;i++)
{
Log.e("Image: "+i+": path", imageList[i].getAbsolutePath());
Bitmap b = BitmapFactory.decodeFile(imageList[i].getAbsolutePath());
images.add(b);
}

Categories

Resources