I am using this code to get the paths of all videos in android
ContentResolver cr = getContentResolver();
String[] proj = {
BaseColumns._ID
};
Cursor c = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if (c.moveToFirst()) {
do
{
int id = c.getInt(0);
Bitmap b = MediaStore.Video.Thumbnails.getThumbnail(cr, id, MediaStore.Video.Thumbnails.MINI_KIND, null);
Log.d("*****My Thumbnail*****", "onCreate bitmap " + b);
ImageView iv = (ImageView) findViewById(R.id.img_thumbnail);
iv.setImageBitmap(b);
}
while( c.moveToNext() );
}
c.close();
But I am getting some id number. I want the real uri of file or content uri. How to get it?
Try this:
ContentResolver cr = getContentResolver();
String[] proj = {
MediaStore.Video.Media._ID,
MediaStore.Video.VideoColumns.DATA
};
...
String ID = c.getLong(c.getColumnIndexOrThrow(MediaStore.Video.VideoColumns._ID));
String DATA_URI = Uri.parse(c.getString(c.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.DATA)));
Related
I'm saving an image loaded with Picasso to be shared afterwards. This is the code I'm using to save it:
String path = MediaStore.Images.Media.insertImage(
mContext.getContentResolver(), mImageBitmap, "Shared image", null);
return Uri.parse(path);
Now, when the image has been shared, I have to delete it using the URI. I've tried some answers I've seen here but none of them has worked. The image still appears in the gallery. These are the methods I have used:
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { new File(mImageUri.toString()).getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c.moveToFirst())
{
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
contentResolver.delete(deleteUri, null, null);
}
c.close();
File file = new File(mImageUri.toString());
// This returns false
file.delete();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(mImageUri.toString()))));
Any idea of what i've done wrong?
Thanks,
Try this for deletion
String[] retCol = { MediaStore.Audio.Media._ID };
Cursor cur = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
retCol,
MediaStore.Images.Media.TITLE + "='"+TEMP_FILE_TITLE+"'", null, null
);
try {
if (cur.getCount() == 0) {
return;
}
cur.moveToFirst();
int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
Uri uri = ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id
);
int cnt = context.getContentResolver().delete(uri, null, null);
}finally {
cur.close();
}
In your case replace TEMP_FILE_TITLE = "Shared image"
I have image files which don't have thumbnails. (imported from my external carmera using NFC)
I want to create thumbnails for my image picker view. (has to be fast)
At this moment, I'm not even sure "MEDIA SCAN" means "generating thumbnail" or what.
I tried to scan file using mMediaScannerConnection.scanFile(mPath, null);
onScanCompleted gets called and I try to get thumbnail using the following two version of functions.
I get null thumbnailPath for both functions, I don't get why..
private String getThumbnailPath(long imageId) {
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = MediaStore.Images.Thumbnails.queryMiniThumbnail(cr, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
try {
if (c.moveToNext()) {
int dataId = c.getColumnIndex( Images.Thumbnails.DATA);
String strThumPath = c.getString(dataId);
Log.i("ScanTest", "strThumPath = " + strThumPath );
return strThumPath;
}
} finally {
if (c != null) c.close();
}
return null;
}
private String getThumbnailPath2( long imageId ){
// http://wikicloud.blogspot.kr/2010/10/scanfile.html
ContentResolver cr = this.mContext.getContentResolver();
Cursor c = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Thumbnails.IMAGE_ID + "= ?" , new String[]{String.valueOf(imageId)}, null);
try {
if (c.moveToNext()) {
int dataId = c.getColumnIndex( Images.Thumbnails.DATA);
String strThumPath = c.getString(dataId);
Log.i("ScanTest", "strThumPath = " + strThumPath );
return strThumPath;
}
} finally {
if (c != null) c.close();
}
return null;
}
-- edit --
Here's how I try to get thumbnails.
first create a mapping from image-id to thumbnail-path.
protected Map getThumbnailPathFromDB() {
Map result = new HashMap();
Cursor thumbCursor = null;
thumbCursor = getContentResolver().query(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
null,
null,
null, null);
if (thumbCursor.moveToFirst()) {
do {
String path = thumbCursor.getString(thumbCursor
.getColumnIndex(MediaStore.MediaColumns.DATA));
long imageId = thumbCursor.getLong(thumbCursor
.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID));
result.put(new Long(imageId), path);
} while(thumbCursor.moveToNext());
}
thumbCursor.close();
return result;
next I iterate all images and try to find thumbnails from the mapping I created above
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(
Images.Media.EXTERNAL_CONTENT_URI, null,
null, null, Images.ImageColumns.DATE_MODIFIED + " DESC");
//thumbnailPathList is the mapping I created above, imageId is the id of image obtained from the cursor
String thumbnailPath = thumbnailPathList.get(new Long(imageId));
// thumbnailPath are occasionally null here!,
I tested my code on about 10 devices.
They all have images which I can't find thumbnails for.
I using the following code to get the thumbnail of JPG and AVI file , but I can not get the thumbnail from .mov files.
String[] projection_image = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, };
String[] projection_video = { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID, };
File file = new File(viewTag.mFileNode.mName) ;
String tempfilePath = file.getPath();
String whereClause_image = MediaStore.Images.Media.DATA + " = '" + tempfilePath + "'";
String whereClause_video = MediaStore.Video.Media.DATA + " = '" + tempfilePath + "'";
ContentResolver cr = getActivity().getContentResolver();
Cursor image_cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection_image, whereClause_image, null, null);
Cursor video_cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection_video, whereClause_video, null, null);
try {
if(image_cursor.moveToFirst()){
long thumID = image_cursor.getLong(image_cursor.getColumnIndex("_ID"));
Bitmap bitmap_image = MediaStore.Images.Thumbnails.getThumbnail(getActivity().getContentResolver(), thumID, Images.Thumbnails.MICRO_KIND, null);
viewTag.mThumbnail.setImageBitmap(bitmap_image) ;
}
if(video_cursor.moveToFirst()){
long thumID = video_cursor.getLong(video_cursor.getColumnIndex("_ID"));
Bitmap bitmap_video = MediaStore.Video.Thumbnails.getThumbnail(getActivity().getContentResolver(), thumID, Video.Thumbnails.MICRO_KIND, null);
viewTag.mThumbnail.setImageBitmap(bitmap_video) ;
}
} catch (NullPointerException e) {
// TODO: handle exception
Log.i(TAG, "cursor---NullPointerException");
image_cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection_image, whereClause_image, null, null);
video_cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection_video, whereClause_video, null, null);
} finally{
image_cursor.close();
video_cursor.close();
}
Does somebody know how to get the thumbnail from .mov files by using MediaStore in Android ?
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
I am trying to retrieve file path from URI. But my cursor is returning null.
Two problems:
Uri may be audio/ video. So how can I retrieve file path.
Why cursor is returning null?
Here is my code
String[] proj = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
//here cursor is null. So i am getting Null pointer exception
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
Permissions I have used:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
public void songList(){
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cur = contentResolver.query(uri, null, null, null, null);
if(cur.moveToFirst()){
do {
int pathIndex = cur.getColumnIndex(MediaStore.Audio.Media.DATA);
int nameIndex = cur.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
String spath = cur.getString(pathIndex);
String name = cur.getString(nameIndex);
paths.add(spath.substring(4));
songs.add(name);
} while (cur.moveToNext());
}
You can use get File path from diffrent SDk versions
Use RealPathUtils for it
public class RealPathUtils {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// 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 = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Now get the file Path from URI
String path = null;
if (Build.VERSION.SDK_INT < 11)
path = RealPathUtils.getRealPathFromURI_BelowAPI11(MainActivity.this, uri);
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
path = RealPathUtils.getRealPathFromURI_API11to18(MainActivity.this, uri);
// SDK > 19 (Android 4.4)
else
path = RealPathUtils.getRealPathFromURI_API19(MainActivity.this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
File file = new File(path);
It was pretty easy to get the Contact picture when querying the People.CONTENT_URI, with a simple
People.loadContactPhoto(activity, ContentUris.withAppendedId(People.CONTENT_URI, contactId)
because I knew the contact Id. Now I need to do the same thing after accesing the Call log. With:
String[] strFields = {
android.provider.CallLog.Calls.CACHED_NAME,
android.provider.CallLog.Calls.NUMBER,
};
String strUriCalls="content://call_log/calls";
Uri UriCalls = Uri.parse(strUriCalls);
Cursor cursorLog = this.getContentResolver().query(UriCalls, strFields, null, null, null);
I get the list from call log, but I can't find any way of linking this with the contact id needed to load the photo. The app works from api level 4+.
Any help is appreciated. Thank you.
The solution, as guided by Cristian below, that works for me is:
private long getContactIdFromNumber(String number) {
String[] projection = new String[]{Contacts.Phones.PERSON_ID};
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL,Uri.encode(number));
Cursor c = getContentResolver().query(contactUri, projection, null, null, null);
if (c.moveToFirst()) {
long contactId=c.getLong(c.getColumnIndex(Contacts.Phones.PERSON_ID));
return contactId;
}
return -1;
}
Then, you must try to get the contact ID by using the queried call log fields. So, you can implement something like this:
private String getContactIdFromNumber(String number) {
String[] projection = new String[]{Contacts.Phones._ID};
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL,
Uri.encode(number));
Cursor c = getContentResolver().query(contactUri, projection,
null, null, null);
if (c.moveToFirst()) {
String contactId=c.getString(c.getColumnIndex(Contacts.Phones._ID));
return contactId;
}
return null;
}
Then, you can use that contact ID to get the photo. Something like this in your case:
cursorLog.moveToFirst();
String number = cursorLog.getString(cursorLog.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
contactId = getContactIdFromNumber(number)
People.loadContactPhoto(activity, ContentUris.withAppendedId(People.CONTENT_URI, contactId);
// blah blah blah
This one works fine for me..
private void contactPickedFromLog(Intent data) {
// TODO Auto-generated method stub
String contactNumber = data.getStringExtra(CONTACT_NUMBER);
Cursor cursor = getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.decode(contactNumber)),
new String[] { PhoneLookup._ID }, null, null, null);
if(cursor.moveToFirst()){
long contactId = cursor.getLong(0);
InputStream inputStream = Contacts.openContactPhotoInputStream(
getContentResolver(),
ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId));
if(inputStream!=null)
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
}
}
I'm doing it in this way:
ContentResolver cr=this.getContentResolver();
Cursor cc = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cc.moveToNext())
{
contactId = cc.getString(cc.getColumnIndex(ContactsContract.Contacts._ID));
Uri contactPhotoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
InputStream is=ContactsContract.Contacts.openContactPhotoInputStream(cr, contactPhotoUri);
//blah-blah
}
Try this ...
public Bitmap getPhoto(String phoneNumber) {
Uri phoneUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Uri photoUri = null;
ContentResolver cr = getContentResolver();
Cursor contact = cr.query(phoneUri,
new String[] { ContactsContract.Contacts._ID }, null, null, null);
if (contact.moveToFirst()) {
long userId = contact.getLong(contact.getColumnIndex(ContactsContract.Contacts._ID));
photoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, userId);
}
else {
Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(), R.drawable.ic_contact_picture);
return getCircleBitmap(defaultPhoto);
}
if (photoUri != null) {
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(
cr, photoUri);
if (input != null) {
return getCircleBitmap(BitmapFactory.decodeStream(input));
}
} else {
Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(), R.drawable.ic_contact_picture);
return getCircleBitmap(defaultPhoto);
}
Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(), R.drawable.ic_contact_picture);
contact.close();
return defaultPhoto;
}
All above answer is correct.You can also get photo by this...
c.getString(c.getColumnIndex(CallLog.Calls.CACHED_PHOTO_URI));
work in SDK >=23
if you are working with minimum SDK...
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(num));
uri = ((phone_uri != null) ? Uri.parse(phone_uri) : uri);
Cursor cursor = getContext().getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
if (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
image_uri = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_URI));
Log.d(TAG, "name " + name + " id "+id+" image_uri "+ image_uri);
}
cursor.close();
}